原题连接:https://www.patest.cn/contests/pat-a-practise/1001
题目如下:
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
______________________________________________________________________________________________________________________________________________________
这道题难点在于如何三位输出,我是利用数组存放每一个数,然后倒序输出,当下标为3的倍数的时候,加入“,”,但有好几个测试点没通过……代码如下:
#include<stdio.h>
#define Max 8 int main()
{
long a,b,sum;
int i,c[Max];
scanf("%d %d",&a, &b);
sum=a+b; if (sum<){printf("-");sum=-sum;}
i=;
c[i]=sum%;
sum/=;
while (sum>)
{
i++;
c[i]=sum%;
sum/=;
}
//printf("%d\n",i);
for (;i>=;i--)
{
printf("%d",c[i]);
if (i%==&&i!=)printf(",");
}
return ;
}
_________________________________________________希望大神能帮我看看我的错误在哪了……
在网上参考了其他人的解法,是直接对sum这个数选取,利用了技巧:取一个数sum(假设该数共有a位)的前n位的时候,用sum/10的(a-n)次方;取它的后n位的时候,用sum%10的n次方,然后就是分情况讨论,因为题中所给a,b是在区间【-1000000,1000000】,将|sum|分为大于1000000,小于1000000而大于1000,大于等于0小于1000的。
代码如下:
#include<stdio.h> int main()
{
int a,b,sum;
scanf("%d %d",&a,&b);
int i;
sum=a+b;
if (sum<){printf("-");sum=-sum;}
if (sum>=)printf("%d,%03d,%03d",sum/,(sum/)%,(sum%));
else if (sum>=)printf("%d,%03d",sum/,sum%);
else printf("%d",sum);
return ;
}