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
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
很水的一道题目,就是输出控制,但是我想了好久
wrong
#include <stdio.h>
#include <string.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
int sum=a+b;
int N=sum;
int s[10];
int i;
int j;
for(i=0; i<3; i++)
{
s[i]=N%1000;
N=N/1000;
}
for(j=2; j>=0; j--)
{
if(sum>=0)
{
if(s[j]!=0&&j!=0)
printf("%d,",s[j]);
if(j==0)
printf("%d",s[j]);
}
if(sum<0)
{
if(j==2)printf("-");
if(s[j]!=0&&j!=0)
printf("%d,",-s[j]);
if(j==0)
printf("%d",-s[j]);
}
}
return 0;
}
提交后是部分错误
我的思路是把要格式化输出的数每三个每三个存到数组里面,再倒序输出,特殊处理最后一个,结果是部分错误;经过验证发现输入“999 1”的时候 输出为“1,0”而不是“1,000”
如果举个例子,这道题目就很好解
比方说要输出“1234567”
如果对应到数组里储存起来应该是
1 2 3 4 5 6 7 |
---|
输出 1,234,567 |
1 2 3 4 5 6 7 |
6 5 4 3 2 1 0 对应数组里面的序号 |
6 5 4 3 2 1 0 倒序输出 |
可以发现1和4后面有逗号,对应数组序号6,3正好是3的倍数
但是要考虑0也是3的倍数,所if条件句中要加入'if (j % 3 == 0 && j)'
“&&j”表示 j 不能为0
AC
#include <stdio.h>
#include <string.h>
int main()
{
int a,b;
int s[10];
scanf("%d%d",&a,&b);
int sum=a+b;
int i=0;
int flag=0;
if(sum<0)
{
flag=1;
sum=-sum;
}
if(sum==0)
printf("0");
while(sum!=0)
{
s[i++]=sum%10;
sum=sum/10;
}
if(flag)printf("-");
int j;
for (j = i - 1; j >= 0; j--)
{
printf("%d", s[j]);
if (j % 3 == 0 && j) printf(",");//J不为0
}
return 0;
}