1001. A+B Format


題目

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;
}

參考

ITEYE博客 - wq611403

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容