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
题目大意及思路:
给定a 与 b,计算a + b 的和,并按规定输出,及没3位输出一个逗号。
使用 ( j % 3 == 0 && j != 0) 来判断是否输出逗号。
代码:
#include<stdio.h>
#include<math.h>
int main(){
int a, b, sum;
int i = 0, j;
int flag[10];
scanf("%d %d", &a, &b);
sum = a + b;
if(sum < 0)
printf("-");
int num = fabs((float)sum);
if(num == 0)
printf("0");
else{
while(num > 0){
flag[i++] = num % 10;
num /= 10;
}
for(j = i-1; j >=0; j--){
printf("%d", flag[j]);
if(j % 3 == 0 && j != 0)
printf(",");
}
}
return 0;
}