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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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 #include<stdio.h>
 2 #include<string.h>
 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<strlen(s);i++){
10         printf("%c",s[i]);
11     if(s[i]=='-')    continue;    //如果为"-"号继续循环不执行以下部分
12     if((i+1)%3==strlen(s)%3&&i!=strlen(s)-1)    //要保证上述所说的情况都要满足
13             printf(",");    
14     }
15 }

 

 
 
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄