【PAT甲级】1001. A+B Format (20)

我太渣了我要从头开始学习如何写代码 ゜(ノД`)・゜

题目:https://www.patest.cn/contests/pat-a-practise/1001

之前自己写的一个:

#include<stdio.h>
int main(){
    int a,b,c;
    char answer[10];
    char reverse[10];
    int i,j,k,count;
    scanf("%d%d",&a,&b);
    c=a+b;
    i=j=k=count=0;
    if(c<0){
        answer[j++]='-';
        c=-c;
    }
    if(c==0) answer[j++]='0';
    else{
    while(c!=0){
        reverse[i++]=(c%10+'0');
        c=c/10;
    }
        k=i;
    for(--i;i>=0;i--,count++){
        if((k-count)%3==0&&count!=0){
            answer[j++]=',';
        }
        answer[j++]=reverse[i];
        }
    }
    for(i=0;i<j;i++)
        printf("%c",answer[i]);
}

从别人那里学来的方法,哇我都没想到printf里的格式控制还能这么用:
(↓ 用g++编译会编译错误,用gcc才行(我为什么会卡在这种error上……

#include<stdio.h>
#include<math.h>

int main() {
    int a, b, c, sum;
    scanf("%d %d", &a, &b);
    sum = a + b;
    c = abs(sum);
    //分成三段来考虑
    if (c < 1000)
        printf("%d", sum);
    if (c >= 1000 && c < 1000000)
        printf("%d,%03d", sum / 1000, c % 1000);
    if (c >= 1000000)
        printf("%d,%03d,%03d", sum / 1000000, (c / 1000) % 1000, c % 1000);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dango_miracle/article/details/79302158
今日推荐