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 #include <iostream>
 4 #include <vector>
 5 #include <sstream>
 6 #include <string>
 7 #include <stack>
 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<string>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 #include <iostream>
 2 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 }

 

转载于:https://www.cnblogs.com/zzw1024/p/11159598.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐