1001 A+B Format (20)(20 分)
Calculate a + b and output the sum in standard format -- that is, thedigits must be separated into groups of three by commas (unless thereare less than four digits).
Input
Each input file contains one test case. Each case contains a pair ofintegers a and b where -1000000 <= a, b <= 1000000. The numbersare 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 9
Sample Output
-999,991
分析:本题的难点在于间隔输出逗号。因为是从低位开始间隔三位,所以开头从哪开始输出逗号是个难题。
解决这个问题要把结果逆序存储在数组里,即a[0]存个位,a[1]存十位,a[2]存百位,数组的末位开始输出,这样从下标是否是3的倍数便可输出逗号,模拟了实际位数(下标)和位数上的数字的表示。
一,正确代码:
#include<iostream>
using namespace std;
int main(){
int num[10];
int a,b,sum;
int len=0;
scanf("%d %d",&a,&b);
sum = a+b;
if(sum<0){
sum=-sum;
printf("-");
}
if(sum==0){
num[len++]=0;
}
while(sum){
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;
}