题目:
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,其中a,b的范围是 −10^6≤a,b≤10^6. 让你求出来a+b的结果,注意每三位要用一个“,”分隔。
思路:
把a+b的结果算出来,然后把结果拆分开,每三位加入一个分隔符“,”;最后注意正负号的输出和分隔符在首尾的位置不需要添加;
代码如下:
#include<stdio.h>
#include<string.h>
#include<string>
#include<math.h>
#include<iostream>
using namespace std;
int a,b;
string s;
int main()
{
while(~scanf("%d%d",&a,&b))
{
int sum=a+b;//计算出来a+b的结果;
if(sum==0)//注意,否则第四组测试数据会错;
printf("0\n");
else
{
s="";//清空字符串;
int fu=0;//符号;
if(sum<0)
fu=1;//注意负号的输出;
sum=fabs(sum);
int k=0;
while(sum!=0)//把数字拆分开存在字符串中,注意每三位加入一个“,”;
{
char tt=sum%10+'0';
sum/=10;
s=s+tt;
k++;
if(k==3)
{
s=s+",";//加入“,”;
k=0;
}
}
if(fu==1)//符号输出;
cout<<"-";
int l=s.size()-1;//注意下标是从0开始的;
if(s[l]!=',')//注意第一位不用添加分隔符;
cout<<s[l];
for(int i=l-1; i>=0; i--)
{
cout<<s[i];
}
cout<<endl;
}
}
return 0;
}