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相加,按照格式输出。-123456输出为-123,456;-1234567输出为-1,234,567
先计算出位数,将数字转换为字符串,根据位数计算逗号的位置即可。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int c = a+b;
if(c<0)
{
cout<<'-';
c=-c;
}
int x=c;
int n=0;// 位数
if(c==0) n++;
while(x!=0){
x/=10;
n++;
}
char s[n];
sprintf(s, "%d", c);
for(int i=0;i<n;i++){
cout<<s[i];
if((n - i - 1)%3==0&&i!=n-1) cout<<',';
}
return 0;
}