1001 A+B Format【PAT (Advanced Level) Practice】

1001 A+B Format【PAT (Advanced Level) Practice】

原题链接:预览题目详情 - 1001 A+B Format (pintia.cn)

1.题目原文

Calculate a + b a + b 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 a a and b b b where − 1 0 6 ≤ a , b ≤ 1 0 6 -10^6 \le a, b \le 10^6 106a,b106. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a a a and b b b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

2. 题目翻译

计算 a + b a + b a+b 并以标准格式输出结果,即数字必须以逗号分隔成每三位一组(除非数字少于四位)。

输入规范:

每个输入文件包含一个测试用例。每个测试用例包含一对整数 a a a b b b,其中 − 1 0 6 ≤ a , b ≤ 1 0 6 -10^6 \le a, b \le 10^6 106a,b106。这两个数字之间用一个空格分隔。

输出规范:

对于每个测试用例,你应该在一行中输出 a a a b b b 的和。和必须以标准格式书写。

示例输入:

-1000000 9

示例输出:

-999,991

3.解题思路

3.1题目分析

  1. 计算两个整数 ab 的和c,由 − 1 0 6 ≤ a , b ≤ 1 0 6 -10^6 \le a, b \le 10^6 106a,b106ab 的和c不超过整型的取值范围。
  2. 将结果以标准格式输出,标准格式要求将数字的每三位用逗号分隔,除非数字少于四位,如输出样例所示,c最多7位数,最多两个逗号。

3.2基本思路

读取输入,求和,按照格式要求输出。

3.3详解步骤

  1. 从标准输入读取两个整数ab
  2. 计算它们的和c
  3. 按照格式要求输出:
    • 如果在 -10001000 之间(不包括 -10001000),直接输出c
    • 否则:
      • 首先判断和c的正负,负数则输出负号,然后将负数转换为正数以便处理。
      • 将和c的每一位数字存储在字符数组s中。
      • 遍历数组元素逐位输出,每三位输出一个逗号,以满足标准格式的要求。

3.4注意要点

每三位输出一个逗号,不需要以三为循环增量来查找输出的位置,因为最多7位数,最多两个逗号,若将要输出的是第三位或第六位数字,则先输出逗号即可。

4.参考答案

#include<stdio.h>

int main(){
    
    
    int a, b, c, i;
    char s[80];

    // 从标准输入读取两个整数
    scanf("%d %d", &a, &b);

    // 计算和
    c = a + b;

    // 判断和的范围,如果在 -1000 到 1000 之间(不包括 -1000 和 1000),直接输出
    if  ((c < 1000) && (c > -1000))
        printf("%d\n", c);
    else {
    
    
        if (c < 0) {
    
    
            printf("-");
            c = -c; // 将负数转为正数以便处理
        }
        i = 0;

        // 将和的每一位数字存储在字符数组 s 中
        while (c) {
    
    
            //对10取余获得最低位,然后转换为对应字符,实现逆序存储
            s[i++] = '0' + c % 10;
            c /= 10;//舍去最低位数字
        }

        i--;

        // 从数组最后往前输出,先输出数组最后一位,即 C 的最高位
        printf("%c", s[i--]);

        // 每三位输出一个逗号
        for (; i >= 0; i--) {
    
    
            //若将要输出的是第三或第六位数字,则先输出逗号
            if ((i == 5) || (i == 2))
                printf(",");
            printf("%c", s[i]);
        }
        printf("\n");
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40171190/article/details/134725362