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 }
相關文章
相關標籤/搜索