zoukankan      html  css  js  c++  java
  • PAT A1001 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 −. 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

    题目大意:给定两个数,计算两个数的和并且按照xxx,xxx,xxx这样的格式输出。
    解题思路:
    (1)计算两数之和。
    (2)和是负数就输出一个符号并将和取绝对值,然后将和按位存入int类型数组中。
    (3)从高位到低位输出数组中的数据,每隔三位输出一个逗号。
    需要注意的点是:和为0的情况不能忽略,还有就是输出注意最后一位不输出逗号。
    #include<iostream>
    
    using namespace std;
    int main() {
    
        int a, b;
        cin >> a >> b;
        int sum = a + b;
        if (sum < 0) { 
            printf("-");
            sum = -sum;
        }
        int res[7];
        int len = 0;//记录长度
        //和为0的情况
        if (sum == 0) res[len++] = 0;
        while (sum) {
            //将sum按位存储,从低位到高位
            res[len++] = sum % 10;
            sum = sum / 10;
        }
        //输出时从高位到低位输出
        for (int i = len - 1; i >= 0; i--) {
            printf("%d", res[i]);
            //每三位输出一个逗号,最后一位除外
            if (i > 0 && i % 3 == 0) printf(",");
        }
        cout << endl;
        system("pause");
        return 0;
    }
     
  • 相关阅读:
    Navicat将表转为模型
    RestTemplate Hashmap变为LinkedHashMap源码解读
    IDEA无法编译源码,IDEA查看源码出现/* compiled code */
    grep,egrep,正则表达式
    特殊权限
    更新系统硬件信息----光驱
    复制其他文件的权限做为自己的权限
    umask
    生成随机口令
    让新增用户默认拥有文件
  • 原文地址:https://www.cnblogs.com/syq816/p/12527387.html
Copyright © 2011-2022 走看看