PAT 1001 A+B Format (20)

来源:互联网 发布:淘宝联盟怎么才能返现 编辑:程序博客网 时间:2024/06/05 11:50

  • 题目英文
  • 题目中文
    • 输入
    • 输出
    • 示例输入
    • 示例输出
  • 思考过程
  • 参考代码1
  • 参考代码2
  • 向下一个题进军

题目英文:

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,",")

向下一个题进军

原创粉丝点击