1001 A + Bフォーマット(20ポイント)

a + bを計算し、合計を標準形式で出力します。つまり、数字は3つのグループにコンマで区切る必要があります(4桁未満の場合を除く)。

入力仕様:

各入力ファイルには、1つのテストケースが含まれています。各ケースには、整数aとbのペアが含まれます。ここで、-106≤a、b≤106です。数字はスペースで区切られます。

出力仕様:

テストケースごとに、aとbの合計を1行で出力する必要があります。合計は標準形式で記述する必要があります。

サンプル入力:

-1000000 9

サンプル出力:

-999,991

例:

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    int c = a + b;
    if(c == 0) {
        cout << 0;
    } else {
        cout << (c > 0 ? "" : "-");
        c = (c > 0 ? c : -c);
        stack<char> s;
        int i = 0;
        while(c) {
            s.push(c % 10 + '0');
            c /= 10;
            ++i;
            if(c && i % 3 == 0) s.push(',');
        }
        while(!s.empty()) {
            cout << s.top();
            s.pop();
        }
    }
    return 0;
}

アイデア:

 スタック、ポップ操作を使用して結果を出力します。

おすすめ

転載: blog.csdn.net/u012571715/article/details/113484933