我的PAT系列文章更新重心已移至Github,歡迎來看PAT題解的小伙伴請到Github Pages瀏覽最新內(nèi)容。此處文章目前已更新至與Github Pages同步。歡迎star我的repo。
題目
Calculate 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
and
where
. The numbers are separated by a
space.
Output Specification:
For each test case, you should output the sum of and
in one line. The
sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
思路
2018/1/5更新0:重要參考鏈接
Stack overflow有一個帖子專門討論如何做這個事情,我自己想到的三個也都是問題里幾個高票答案的方法,大家可以學習一下。
兩個要點:
- 兩數(shù)和為0時要輸出0;
- 注意逗號的輸出位置,如不要在數(shù)字前面和后面有輸出
2018/1/5更新1:
又看了一遍題,總感覺之前的代碼太繁瑣,就改了一個方法,使用字符串處理。
得到a和b后,將兩者之和輸入到一個字符串中去,使用sprintf
函數(shù)。
只需要從后向前,每三個數(shù)字判斷一下是否需要加逗號即可。
2018/1/5更新2:
還有一種更省事的方法,甚至C語言里都有直接的方法處理這種事情。那就是<locale.h>頭文件,這個頭文件可以處理不同地區(qū)或者語言的輸出方式,其中就有對數(shù)字的處理。具體細節(jié)可查看相關資料,代碼放在下面
#include <stdio.h>
#include <locale.h>
int main(void)
{
setlocale(LC_NUMERIC, "");
printf("%'d\n", 1123456789);
return 0;
}
代碼
最新代碼@github,歡迎交流
#include <stdio.h>
#include <string.h>
int main()
{
int a, b, pos;
char num[11];
scanf("%d%d", &a, &b);
sprintf(num, "%d", a + b);
for(pos = strlen(num) - 3; pos > 0 && num[pos - 1] != '-'; pos -= 3)
{
memmove(num + pos + 1, num + pos, strlen(num) - pos + 1);
num[pos] = ',';
}
puts(num);
return 0;
}