1001. A+B Format (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 9Sample Output
-999,991
【分析】"输出a+b"问题的变形
这里要求每3位数中间用一个' , '隔开,因此可用result保存a+b的结果。其中当result=0时直接输出0 当result>0时进行数位分离,然后输出时每输出3位打印一个',' 当result<0时打印一个'-',然后取其相反数转换为result>0的情形
#include <stdio.h>
int main()
{
int a,b;
int i,result;
int len,digit[10];
scanf("%d %d",&a,&b);
result=a+b;
len=0;
if(result<0)
{
printf("-");
result=-result;
}
if(result==0)
printf("0\n");
else
{
while(result!=0)
{
digit[len++]=result%10;
result/=10;
}
//每输出3位打印一个',',注意最高位前面没有','
for(i=len-1;i>=0;i--)
{
printf("%d",digit[i]);
if(i%3==0 && i!=0)
printf(",");
}
printf("\n");
}
return 0;
}