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
1、理解题意
给出两个整型数a和b,计算总和sum,将sum输出时每三个数字就输出一个逗号,数字末尾不用输出逗号,数字的正负号不算在内。
2、解题思路
(1)数组法:将sum中的数字依次存放到数组num中,数字高位对应数组高位,输出时从高位开始输出;如果sum为负数,则先输出负号,再取相反数;特殊情况当sum为0时要特判。
#include<cstdio>
int main(){
int a,b;
int sum;
scanf("%d %d",&a,&b);
sum=a+b;
if(sum<0){
printf("-");
sum=-sum;
}
int num[10];
int len=0;
if(sum==0) printf("0");
while(sum!=0){
num[len++]=sum%10;
sum/=10;
}
for(int i=len-1;i>=0;i--){
printf("%d",num[i]);
if(i>0&&i%3==0){
printf(",");
}
}
return 0;
}
3、总结
(1)本题可以使用常规方法数组法,也可以使用字符串法,将sum结果直接转化为字符串。