1001 A+B 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).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where 106a,b106. 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

 

思路:

当输出多行数值时,一定要注意是否有多余或缺少空行的情况

将 int 转换为 string 可以直接使用 to_string(x)

使用string 代替char数组的好处是 可以使用string自带的函数简化代码,提高效率。

 

代码:

 

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int main(){
    int a,b,sum,t=0,l;
    char s[100];
    while(scanf("%d%d",&a,&b) != -1){
        sum = a + b;
        sprintf(s, "%d", sum);
        if(s[0] == '-'){
            if(strlen(s) < 5){
                cout<<s;
            }else{
                cout<<s[0];
                l = strlen(s) - 1;
                for(int i=1; i<=l % 3; i++){
                    cout<<s[i];
                }
                if(l % 3 != 0) cout<<",";
                t = 0;
                for(int i=l % 3 + 1; i < strlen(s); i++){
                    cout<<s[i];
                    t++;
                    if(t == 3 && i != strlen(s) - 1){
                        cout<<",";
                        t = 0;
                    }
                }
            }
        }
        else{
           if(strlen(s) < 4){
               cout<<s;
           }else{
                l = strlen(s);
                for(int i=0; i<l % 3; i++){
                    cout<<s[i];
                }
                if(l % 3 != 0) cout<<",";
                t = 0;
                for(int i=l % 3; i < strlen(s); i++){
                    cout<<s[i];
                    t++;
                    if(t == 3 && i != strlen(s) - 1){
                        cout<<",";
                        t = 0;
                    }
                }
           }
        }
        cout<<endl;
    }
    return 0;
}

 

 

简化代码:

#include <iostream>
using namespace std;
int main() {
    int a, b;
    cin >> a >> b; //输入a和b
    string s = to_string(a + b); //将a+b的值转换为字符串
    if(s[0] == '-') { //处理符号
        cout << '-';
        s.erase(0, 1);
    }
    int count = 0; //用于记录当前位置
    for(int i = s.length() - 1; i >= 0; i--){ //添加逗号
        count++;
        if(count % 3 == 0 && i > 0){
            s.insert(i, ",");
        }
    }
    cout << s;
}

 

原文地址:http://www.cnblogs.com/yccy/p/16883770.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性