PAT1001

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

Calculate a + b and output the sum in standard format

计算a+b并且输出标准形式的和

-- 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.

对于每一个输入文件包含一个测试用例。每个测试用例包含一对数a和b,-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.

对于每个测试用例,你需要在一行中输出ab的和。这个和必须以标准的形式被写出。

Sample Input

-1000000 9

Sample Output

-999,991
 
简单题目,主要问题在于格式。
然后有两个比较好的技巧,一个是提前处理0,防止除数为0。还有一个是提前处理负数的请求。
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    char ch[20];//用于存放最终输出的数据
    int a,b,c;
    int i=0,j=0;
    cin>>a>>b;
    c=a+b;
    //提前处理0的请求
    if(c==0)
    {
        cout<<0;
    }
    else
    {
        //化负数为正数,提前处理请求
        if(c < 0)
        {
            cout<<"-";
            c=-c;
        }
        while (c>=10)
        {
            ch[i] = c%10 + '0';
            c/=10;
            i++;
            //用J来记录访问位数为3的逗号
            if((i-j)%3 == 0)
            {
                ch[i] = ',';
                j++;
                i++;
            }
        }
        ch[i] = c + '0';

        //循环输出最后的结果
        for (;i>=0;i--)
            cout<<ch[i];
    }
    return 0;  
}
 
网上还看到一个比较取巧的方法。
#include<stdio.h>  
int main()  
{  
  int a,b;  
  int sum;  
  while(scanf("%d%d
",&a,&b) != EOF){  
        sum = a+b;  
    if(sum < 0){  
    printf("-");  
    sum = -sum;  
    }  
    if(sum>=1000000){  
        printf("%d,%03d,%03d
",sum/1000000, (sum/1000)%1000, sum%1000);  
    }  
    else if(sum >= 1000){  
        printf("%d,%03d
",sum/1000,sum%1000);  
    } else{  
        printf("%d
", sum);  
    }  
  }  
  return 0;  
}
原文地址:https://www.cnblogs.com/linkstar/p/5668245.html