PAT (Advanced Level) Practice 1001 A+B Format (20 分)

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

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>
#include <math.h>
using namespace std;
stack<int>re;
int a,b,c;
int flag=0;
int main()
{
    scanf("%d%d",&a,&b);
    int c=a+b;
    if(c==0)
    {
        printf("0\n");
        return 0;
    }
    if(c>0)
        flag=1;
    while (c)
    {
       re.push(c%1000);
       c/=1000;
    }
    if(!flag)
        printf("-");
    int Size=re.size();
    for (int i=0;i<Size;i++)
    {
        int temp=re.top();
        re.pop();
        if(i)
        printf("%03d",abs(temp));
        else
        printf("%d",abs(temp));
        printf("%c",i==Size-1? '\n':',');
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/82813887