数组I 问题AK : 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).

输入

Only one line. Contains two integers a and b(-1000000≤a, b≤1000000). The numbers are separated by a space.

输出

Only one line. Output the sum of a and b in one line. The sum must be written in the standard format.

样例输入 Copy

-1000000 9

样例输出 Copy

-999,991

题目意思:
输入a和b,计算a+b,输出按三位一个","的格式.

这个题目一开始我打算直接 %1000 然后输出一个 ","然后判断是否>1000之类的,但是最终结果是反过来的不能逆序输出,直接换成老师讲过的这个思路。

先看正负。
然后判断位数。
逆序输出,如果输出三个之后输出一次 “ , ” 最后一个0的时候不输出,over。
#include <bits/stdc++.h>
using namespace std;

int main()
{
    long long a,b,n,x[100];
    cin>>a>>b;
    n=a+b;
    if(n<0)
    {
        cout<<"-";
        n=-n;
    }
    int cnt;
    cnt=log10(n)+1;
    int i=0;
    while(n)
    {
        x[i]=n%10;
        n=n/10;
        i++;
    }
    for(int i=cnt-1;i>=0;i--)
    {
        cout<<x[i];
        if(i%3==0&&i!=0)
        {
            cout<<",";
        }
    }
    return 0;
}

难度不大

评论

暂无评论