1001 A+B Format

作者: 飞白非白 | 来源:发表于2019-01-10 12:52 被阅读1次

    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

    源代码

    //
    // Created by sir Tian on 2019/1/10.
    //
    #include <stdio.h>
    
    #include <math.h>
    
    // 用于将数字转化为 字符数组
    void getFormatInt(int num, char result[])
    {
    
        int i;
        int remain = num;
        for (i = 0; remain > 0; i++)
        {
            result[i] = (remain % 10) + '0';
            remain /= 10;
        }
        result[i] = '\0';
    }
    
    int main()
    {
    
        // factor_a,factor_b分别用来保存输入的两个相加的数,sum用于保存加数的和
        long factor_a, factor_b, sum = 0;
    
        // 两个数最大为10的六次方,其和最大不超过八位
        char ch[9];
    
        scanf("%ld %ld", &factor_a, &factor_b);
    
        // 两个数求和
        if (factor_a >= -pow(10, 6) && factor_a <= pow(10, 6) &&
            factor_b >= -pow(10, 6) && factor_b <= pow(10, 6))
        {
            sum = factor_a + factor_b;
        }
    
        // 如果和为负数则先把符号输出
        if (sum < 0)
        {
            printf("-");
            sum = 0 - sum;
        }
    
        // 将数的各个位保存到数组中
        getFormatInt(sum, ch);
    
        // 求数组的长度,便于控制在指定的位置输出分隔符号
        int i;
        for (i = 0; ch[i] != '\0'; i++)
        {
        }
    
        // 从数组后面向前输出
        for (int j = i - 1; j >= 0; j--)
        {
            printf("%c", ch[j]);
            // 从后往前数索引是三的倍数则需要输出一个分隔符,如果位置是0则不用输出
            if (j % 3 == 0 &&  j!=0)
            {
                printf(",");
            }
        }
    
        printf("\n");
    
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:1001 A+B Format

        本文链接:https://www.haomeiwen.com/subject/sltarqtx.html