A1001A+Bforamt
Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
思路:
判断sum正负,若为负输出-,然后将sum的绝对值存到字符串c中;遍历c,每三个元素且不是最后一个元素时输出逗号。
问题:
部分测试用例答案错误
解决:
从高位开始每三位加一个,这样最低一组可能不足三个,改成,从低位开始每三位一组。给出的样例太有迷惑性了…
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int main() { 5 int a, b; 6 cin >> a >> b; 7 int sum = a + b; 8 if (sum < 0)cout << "-"; 9 string c = to_string(abs(sum)); 10 int len = c.length(); 11 for (int i = 0; i < len; i++) { 12 cout << c [i]; 13 if ((i+1) % 3 == len%3 &&i!=len-1) 14 cout << ","; 15 } 16 return 0; 17 }
作者:PennyXia
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。