您的位置:首页 > 其它

PAT甲级1001题解

2017-03-18 20:30 232 查看
题目要求如下:

1001. A+B Format (20)

时间限制
400 ms

内存限制
65536 kB

代码长度限制
16000 B

判题程序
Standard

作者
CHEN, Yue

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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


注:这题是一道简单题,但是前几次提交都拿不到所有测试点,容易有所遗漏。比如1+1,输出002,还有-1+1未输出等低级错误。

(talk is cheap,show me the code.coding......)

#include<stdio.h>

#include<stdlib.h>

int number[10];

int main()

{

    int a, b;

    bool flag;//用于标记是否为负数

    int sum;

    while (scanf("%d%d", &a, &b) != EOF)

    {

        flag = 0;

        sum = a + b;

        if (sum < 0)

            flag = 1;

        if (flag == 1)

        {

            sum = -sum;

            printf("-");

        }

        //int count = 0;

        int i = 0;

        if (sum == 0)

            printf("%d", 0);

        bool flag2 = 0;//用于标记是否小于1000

        if (sum < 1000)

            flag2 = 1;

        while (sum)

        {

            number[i++] = sum % 1000;

            sum /= 1000;

        }

        for (int j = i - 1; j >0; j--)

        {

            if (j != i - 1)

                printf("%03d,", number[j]);

            else

                printf("%d,", number[j]);

        }

        if (i >= 1)

        {

            if (flag2 == 0)

                printf("%03d", number[0]);

            else

                printf("%d", number[0]);

        }

        printf("\n");

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: