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 9
Sample Output
-999,991
本题很简单,但是要注意最高位的输出,最高位的输出不需要在前面添加0。
#include <iomanip>头文件才能使用一下方法:
setw(n)设置输出列宽setfill(char)填充空余位置
#include <math.h>:
pow(n,exp)指数函数
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main() {
int a, b,sum,i=0;
cin >> a >> b;
sum = a + b;
if (sum < 0) {
cout << "-";
sum = -sum;
}
for (int tmp=sum/1000; tmp != 0; i++){
tmp /= 1000;
}
int tmp = sum / (int)pow(1000, i);
cout<<tmp;
sum = sum % (int)pow(1000, i);
i--;
for (; i>=0; i--){
cout << ",";
tmp = sum / (int)pow(1000, i);
//if (tmp < 10) cout << "00";
//else if (tmp < 100) cout << "0";
//cout << tmp;
cout << setfill('0') << setw(3) << tmp;
sum = sum % (int)pow(1000,i);
}
system("pause");
return 0;
}