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 −10
6
≤a,b≤10
6
. 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
思路:直接相加,求余用数组存放,倒序输出。
注意:1000以内数的处理,以及负数的输出。
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
int main()
{
int a,b,i=0,j,k=0,s[7],sum;
cin>>a>>b;
sum=a+b;
if(sum<1000&&sum>-1000)
{
cout<<sum<<endl;
}
else
{
if(sum<0)
{
k=1;
sum=-sum;
}
while(sum>0)
{
s[i++]=sum%10;
sum=sum/10;
}
if(k==1) cout<<"-";
for(j=i-1;j>0;j--)
{
cout<<s[j];
if(j%3==0) cout<<",";
}
cout<<s[0]<<endl;
return 0;
}
}