题目链接:http://www.patest.cn/contests/pat-a-practise/1001
题面:
1001. A+B Format (20)
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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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 9Sample Output
-999,991
题意大意:
输出a+b,以每三位加一个逗号的格式。
解题:
注意后面部分假设小于100需加前缀0。
代码:
#include <cstdio> #include <vector> #include <iostream> #include <string> #include <algorithm> #include <iomanip> using namespace std; int main() { int a,b,ans; cin>>a>>b; ans=a+b; if(ans<0) { cout<<"-"; ans=-ans; } if(ans<1000) cout<<ans<<endl; else if(ans<1000000) cout<<ans/1000<<","<<fixed<<setw(3)<<setfill('0')<<ans%1000<<endl; else cout<<ans/1000000<<","<<fixed<<setw(3)<<setfill('0')<<ans/1000-ans/1000000*1000<<","<<fixed<<setw(3)<<setfill('0')<<ans%1000<<endl; return 0; }