pat1001 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 −. 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的和并从右往左每三位加一个","正序输出,大致思路为将计算的数转换为字符后,然后一位一位输出,同时判断何时该加“,”。 难点在于这个地方,存在以下两种情况:1、若整个a+b和的位数是3的倍数,则重点考虑如何判断最后一位之后不加“,”如“324,113”不能为“324,113,”。 2、若整个a+b和的位数不是3的倍数,则重点考虑如何实现从右往左每三位加一个“,”。
关键代码:
1 (i+1)%3==strlen(s)%3&&i!=strlen(s)-1 //s为数字转换后的字符数组
完整代码:
1 #include2 #include 3 int main() 4 { 5 int a,b,i; 6 char s[10]; 7 scanf("%d %d",&a,&b); 8 sprintf(s, "%d", a+b); //将数字转换为字符数组 9 for(i=0;i