A1001 A+B Format (20分)【C语言】
晴神给出了两种解题方法:
- 直接输出。直接控制最后的输出格式进行输出(但是晴神在书里说用**%3d**进行输出时不满三位的用空格补齐,但是由本题题意来看并不需要补齐,直接输出即可)
- 数组输出。注意最后的格式控制。
题目描述:
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).
输入格式:
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.
输出格式:
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.
输入样例:
-1000000 9
输出样例:
-999,991
实现代码1(直接输出):
#include <stdio.h>
int main()
{
int a, b, sum;
scanf("%d %d", &a, &b);
sum = a + b;
if(sum<0){
printf("-");
sum = -sum;
}
if(sum>=1000000) printf("%d,%03d,%03d", sum/1000000, sum%1000000/1000, sum%1000);
else if(sum>=1000) printf("%d,%03d", sum/1000, sum%1000);
else printf("%d", sum);
return 0;
}
实现代码2(数组输出):
#include <stdio.h>
int main()
{
int a, b, sum, len=0, num[10], i;
scanf("%d %d", &a, &b);
sum = a + b;
if(sum<0){
printf("-");
sum = -sum;
}
do{
num[len++] = sum % 10;
sum /= 10;
}while(sum);
for(i=len-1; i>=0; --i){
printf("%d", num[i]);
if(i>0 && i%3==0) printf(","); // 除最后一组外,每三个数字一个逗号
}
return 0;
}