PAT 1001 A+B Format (20)

题目英文:

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

题目中文

计算a+b并且以标准格式输出,这意味着,数字必须每三个以逗号分隔(除非少于四个字符)。

输入

每个输入文件包含一个测试用例。每个测试用例包含一对a和b,其中a>=-1000000,b<=1000000.数字以空格分隔。

输出

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

示例输入

-1000000 9

示例输出

-999,991

思考过程

首先,测试用例不可知,但是经过满分测算,发觉所有测试数据都没有超过-1000000=

参考代码1:

自己写的第一版代码 low爆了,但是还是贴上去了,不管怎样,终究是自己写的,作为第一次通过的感觉好开心。
注意:
由于第一次使用这个测试系统,习惯性的void main,结果导致返回值各种问题,实际上应该是int main()然后return 0,系统对返回值为非0(void也是非0)都直接认为错误!!!!
估计测试程序是执行多次的,所以其实没有while也是可以的

#include<stdio.h>
int main()
{
        int a ,b ,sum,len;
        char tempA[12];
        char tempB[12];
        int isnegative;
        int i = 0,j = 0;
        while(scanf("%d %d",&a,&b)!= EOF)
        {
                isnegative = 0;
                j = 0;
                sum = a + b;
                if(sum < 0){
                        isnegative = 1;
                        sum = abs(sum);
                }
                sprintf(tempB,"%d",sum);
                len = strlen(tempB);
                for(i=0;i<len;i++){
                        if(j%4 == 3)
                                tempA[j]=',', j++;
                        tempA[j++] = tempB[len-i - 1];
                }
                tempA[j] = '\0';
                len = strlen(tempA);
                if(isnegative == 1){
                        tempB[0]='-';
                        j=1;
                }else{
                        j=0;
                }
                for(i = 0;i<len;i++)
                        tempB[j++] = tempA[len-i-1];
                tempB[j] = '\0';
                printf("%s\n",tempB);
        }
        return 0;
}

参考代码2:

还是python代码简单,啥也不说了:

a = raw_input()
dirt = a.split()
total = int(dirt[0]) + int(dirt[1])
print format(total,",")

向下一个题进军

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值