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 Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10​^6​​≤a,b≤10^​6​​. The numbers are separated by a space.

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。要求结果用“三位分节法”来表示。

#include <bits/stdc++.h>

using namespace std;

int a[15];

int main() {
    int n, m, t = 1;

    scanf("%d %d", &n, &m);
    n = n + m; // add
    if (n == 0) // sum = 0
        printf("0");
    else {
        if (n < 0) // negative number
            printf("-");
        n = abs(n);
        while (n) { // Reverse order
            a[t++] = n % 10;
            n /= 10;
        }
        int p = (t-1) % 3;
        for (int i = 1; i <= p; i++)
            printf("%d", a[t - i]);
        if (p < t - 1 && p)
            printf(",");

        for (int i = 1; i < t - p; i++) {
            printf("%d", a[t - p - i]);
            if (i % 3 == 0 && i != t - p - 1)
                printf(",");
        }
    }
    return 0;
}

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐