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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. 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
解题思路先读入a和b求和c,因为是三位三位分割,所以用一个循环,每次循环让把c%1000存进栈里面,再让c/=1000(存进数组倒序输出也是一样的),因为c可能为0,所以用do while循环,保证至少有一次循环,循环结束条件为c!=0。因为c可能为负数,负数对1000取模也是负数,所以要先取个绝对值。输出的时候不要忘了负号,还有要注意第一个输出直接输出第一个出栈的内容,后面的可能会只有一位数两位数,所以用printf的格式化输出"%03d"。
代码如下
#include <iostream>
#include <stack>
#include <cmath>
#include <cstdio>
using namespace std;
int main()
{
int a, b;
while(cin >> a >> b){
int res = a + b;
bool flg = true;
if(res < 0)
flg = false;
stack<int> sta;
res = abs(res);
do{
sta.push(res%1000);
res /= 1000;
}while(res);
if(!flg)
cout << "-";
bool first = true;
while(!sta.empty()){
if(first){
first = false;
cout << sta.top();
}
else {
cout << ",";
printf("%03d", sta.top());
}
sta.pop();
}
cout << endl;
}
return 0;
}