PAT甲题题解-1001. A+B Format (20)-字符串处理,水

计算A+B的和,并且按标准格式处理,每3个就要有个逗号

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

int main()
{
    int a,b;
    scanf("%d %d",&a,&b);
    int sum=a+b;
    char str[20];
    sprintf(str,"%d",sum); //将num按指定格式输入到str字符串中
    int idx=0;
    if(sum<0){
        printf("-");
        idx=1;
    }
    int len=strlen(str);
    for(int i=idx;i<len;i++){
        printf("%c",str[i]);
        int left=len-i-1;
        //剩下的个数是3的倍数的话,就要输出','。当然最后一位除外
        if(left%3==0 && i!=len-1)
            printf(",");
    }
    printf("\n");
    return 0;
}
View Code

 

posted @ 2017-04-18 14:51  辰曦~文若  阅读(943)  评论(0编辑  收藏  举报