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 很简单,数字转字符串即可
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include4 #include 5 #include 6 #include 7 #include 8 9 using namespace std;10 11 int main()12 {13 int a, b,sum;14 string str;15 scanf("%d %d", &a, &b);16 sum = a + b;17 stringstream ss;18 ss << sum;19 ss >> str;20 21 ///此处可以通过sum/1000,然后转为字符串22 stack res;23 int k;24 string s;25 for (k = str.length(); k > 3;k-=3)26 { 27 s.assign(str.begin() + k - 3, str.begin() + k);28 res.push(s);29 res.push(",");30 }31 s.assign(str.begin(), str.begin() + k);32 if (s == "-")33 res.pop();34 res.push(s);35 while (!res.empty())36 {37 cout << res.top();38 res.pop();39 }40 return 0;41 }
更简洁点
1 #include2 using namespace std; 3 int main() { 4 int a, b; 5 cin >> a >> b; 6 string s = to_string(a + b); 7 int len = s.length(); 8 for (int i = 0; i < len; i++) { 9 cout << s[i];10 if (s[i] == '-') continue;11 if ((i + 1) % 3 == len % 3 && i != len - 1) cout << ",";12 }13 return 0;14 }