PAT 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 −106​​ ≤a,b≤106. 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的值并按标准格式输出结果。标准格式即:数字需将每三位用逗号(,)分隔开,除非数字的位数小于4位。
输入一对整数a和b,在一行内以标准格式输出a和b的和。

题解

题目过于简单,懒得写注释了。
C语言gcc 6.5.0代码如下:

#include<stdio.h>
#include<math.h>
int main(){
    int a, b;
    scanf("%d %d", &a, &b);
    int sum = a + b;
    if(sum < 0){
        printf("-");
        sum = -sum;
    }
    if(sum >= 1000000){
        printf("%d,", sum/1000000);
        sum -= sum/1000000 * 1000000;
        printf("%03d,", sum/1000);
        sum -= sum/1000 * 1000;
        printf("%03d\n", sum);
    }
    else if(sum >= 1000){
        printf("%d,", sum/1000);
        sum -= sum/1000 * 1000;
        printf("%03d\n", sum);
    }
    else
        printf("%d\n", sum);
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容