PAT日志 1001

顽强的小白

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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​​≤a,b≤10​6​​. The numbers are separated by a space.

Output Specification:
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

代码实现

#include <cstdio>
#include <cstring>
using namespace std;
void deal(int num){ 
 char pp[20],temp;
 int t,i=0;
 if(num<0){
  printf("-");
  num=-num;
 }
 int cnt=1;
 while(num!=0){
  t=num%10;
  pp[i++]=t+'0';
  num=num/10;
  if(cnt%3==0&&num!=0){
   pp[i++]=',';
  }
  cnt++;
 }
 for(int j=i-1;j>=0;--j){
  printf("%c",pp[j]);
 }
}
int main(){
 int a,b,sum;
 scanf("%d %d",&a,&b);
 sum=a+b;
 deal(sum)}

注意点

既然是学习日志,我就的记得详细点,有点啰嗦也认了,希望自己后面再来看看

  • 第一个测试点分值最大;
  • 负数的处理简单明了;
  • 计算不是难点,(其实这道题不难)主要是输出,要把数字按照每三位输出一个逗号,我把数字转换成了字符串储存起来,然后把逗号加进去,因为在转换成字符的时候用的最常用的除余数法,得到的结果是倒着的,因此正好符合加逗号的规则(逗号是从个位向高位数着加的),最后不能在最前面加逗号,也确实有这个测试点,注意看我加了一个条件sum!=0
    字符串成形之后倒着输出就行啦,不需要逆转;
  • 结果为零的输出要单独处理,只要注意到就没什么事了;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值