[PAT甲级] 1001 A+B Format (20分)

发布于 2021-01-24  1477 次阅读


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(大小为−10​6≤a,b≤10​6),格式化输出一个整数,要求从右到左每隔三位加一个','

AC CODE:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#include<cstring>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
#define MAXN 250005
#define MAXSIZE 10
#define DLEN 4
#define mod 1000000007
const int MOD = 1e9+7;

int main(){
    int a,b;
    scanf("%d%d",&a,&b);
    int c=a+b;
    if(c>=1000||c<=-1000){//如果在1000~-1000则不用进行任何操作
        int flag=(c>0)?1:(c=-c,0);//flag记录运算结果的正负,并取计算结果绝对值
        char cc[10]={'0'};//运算结果保存为字符型
        int i=0;
        while(c!=0){
            cc[i++]=(char)(c%10+48);//取最左边一位(字符‘0’ascii码为48)
            c/=10;
            if(i==3&&c!=0)cc[i++]=',';
            if(i==7&&c!=0)cc[i++]=',';
        }
        i--;
        if(flag){
            for(;i>=0;i--)
                printf("%c",cc[i]);
        }else{
            printf("-");
            for(;i>=0;i--)
                printf("%c",cc[i]);
        }
        
    }else{
        printf("%d\n",c);
    }
    return 0;
}

届ける言葉を今は育ててる
最后更新于 2021-01-24