題目
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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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的和,并輸出,每三位輸出一個逗號。
思路
一看到題目就想到把和的每一位拆分存進數(shù)組,再按序進行判斷輸出,負號的情況要單獨討論。結(jié)果做出來是可行的,要注意的是要考慮sum=0的特殊情況。
后來覺得題目這么短,怎么代碼這么長,很難受,就網(wǎng)上查了一下,果不其然,和別人的一比自己寫的真的是low B······主要還是C基礎(chǔ)沒學(xué)好,對輸出的格式語句沒有深入研究過,下簡要記錄一下權(quán)當(dāng)學(xué)習(xí)了:
%d 正常輸出
%3d 指定寬度,不足的左邊補空格
%-3d 左對齊輸出
%03d 指定寬度,不足的左邊補0
代碼實現(xiàn)Ⅰ
#include <stdio.h>
#include <math.h>
int main(void)
{
int a, b, sum;
int flag = 0; // flag用來判斷sum是否為負數(shù)
int arr[10]; // 存放各位數(shù)字及逗號
int count = 0; // 位數(shù)計數(shù)
int i = -1; // 數(shù)組下標及長度
scanf("%d %d", &a, &b);
sum = a + b;
if (sum < 0)
{
flag = 1;
sum = abs(sum);
}
/*sum = 0特殊情況*/
if(sum == 0)
{
printf("0");
return 0;
}
/*數(shù)組創(chuàng)建*/
while (sum != 0)
{
if (count == 3)
{
arr[++i] = -1; // 若為逗號存-1
count = 0;
}
else
{
arr[++i] = sum % 10;
++count;
sum /= 10;
}
}
/*輸出*/
if (flag)
{
printf("-");
flag = 0;
}
for (int j = i; j >= 0; --j)
{
if (arr[j] == -1)
{
printf(",");
continue;
}
else
printf("%d", arr[j]);
}
return 0;
}
代碼實現(xiàn)Ⅱ
#include <stdio.h>
int main()
{
int a, b;
int sum;
while (scanf("%d%d\n", &a, &b) != EOF) {
sum = a + b;
if (sum < 0) {
printf("-");
sum = -sum;
}
if (sum >= 1000000){
printf("%d, %03d, %03d\n", sum / 1000000, (sum / 1000) % 1000, sum % 1000);
}
else if (sum >= 1000) {
printf("%d, %03d\n", sum / 1000, sum % 1000);
} else {
printf("%d\n", sum);
}
}
return 0;
}
參考