1001 A+B Format (20)(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
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 9
Sample Output
-999,991
翻译:
1001 A+B Format (20)(20 分)
计算a + b并以标准格式输出总和 - 也就是说,数字必须用逗号分隔成三个组(除非少于四位数)。
输入
每个输入文件都包含一个测试用例。每个案例包含一对整数a和b,其中-1000000 <= a,b <= 1000000。数字之间用空格分隔。
产量
对于每个测试用例,您应该在一行中输出a和b的总和。总和必须以标准格式编写。
关键在于:用逗号隔开每三个数,要计算好逗号的位置。
实现方式:int类型输入,使用sprintf()函数转化为字符串数组,计算好位置再输出。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define N 15
int main()
{
int a, b, sum;
char c[N];
while ((scanf("%d %d", &a, &b) != EOF))
{
sum = a + b;
if (sum < 0)
{
printf("-");
sum = -sum;
}
sprintf(c, "%d", sum);
for (int i=0; c[i]!='\0'; i++)
{
printf("%c",c[i]);
if ((strlen(c)-i-1)%3 == 0 && i!=(strlen(c)-1))
{
printf(",");
}
}
break;
}
return 0;
}
再贴一个更简单的实现方法:
#include<stdio.h>
int main()
{
int a, b, c;
int sum;
c = scanf("%d%d", &a, &b);
while( c != EOF){
sum = a+b;
if(sum < 0){
printf("-");
sum = -sum;
}
if(sum>=1000000){
printf("%d,%03d,%03d\n",sum/1000000, (sum/1000)%1000, sum%1000);
}
else if(sum >= 1000){
printf("%d,%03d\n",sum/1000,sum%1000);
} else{
printf("%d\n", sum);
}
exit(0);
}
return 0;
}