pat甲级题目1001 A+B Format详解

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).html

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.git

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的和并从右往左每三位加一个","正序输出,大体思路为将计算的数转换为字符后,而后一位一位输出,同时判断什么时候该加“,”。
难点在于这个地方,存在如下两种状况:一、若整个a+b和的位数是3的倍数,则重点考虑如何判断最后一位以后不加“,”如“324,113”不能为“324,113,”。
二、若整个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 }
相关文章
相关标签/搜索