Fork me on GitHub

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\n",&a,&b) != EOF){  
        sum = a+b;  
    if(sum < 0){  
    printf("-");  
    sum = -sum;  
    }  
    if(sum>=1000000){  
        printf("%d,%03d,%03d\n",sum/1000000, (sum/1000)%1000, sum%1000);  
    }  
    else if(sum >= 1000){  
        printf("%d,%03d\n",sum/1000,sum%1000);  
    } else{  
        printf("%d\n", sum);  
    }  
  }  
  return 0;  
}
复制代码
posted @   LinkinStar  阅读(333)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示