pat 甲级 A1001 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

题目大意:

给两个整数a,b,计算并输出两者的和,输出格式为从低到高为,每三位输出一个逗号(commas),如果位数为3的倍数或者位数小于等于3,那么就不用输出最高位后输出逗号。

思路分析:

 定义整型变量a,b,c,接着利用整型数组s[8]保存a加b之和c的各位,然后设置一个工作变量i,从高位开始输出数组s[8],先输出s[i],若i%3==0,则输出','(不妨考虑结果c不止三位,在输出s[3]后,根据要求此时得输出一个逗号,对于6,9,...,3i,...同理,注意i==0时不用再输出逗号,因此我们可以将i不为0作为循环条件),最后单独输出s[0]。

参考代码:

#include <iostream>
using namespace std;

int main()
{
   int a,b,c;
   int s[8];
   int i=0;
   cin>>a>>b;
   c=a+b;
   if(c<0){
       cout<<'-';
       c=-c;
   }
   while(c){
    s[i++]=c%10;
    c/=10;
   }
   i-=1;
   while(i){
    cout<<s[i];
    if(i%3==0){
        cout<<',';
    }
    i-=1;
   }
   cout<<s[0]<<endl;
}

 

 此时,出现段错误(数组越界或者堆栈溢出),开始的我,改了很多地方QAQ,,,不太懂哪里出现问题,最后想了一下,若果在i到第二个while判断之前,已为-1,此时将出现死循环,根据这一点推出若a+b的结果c为0,则直接输出0即可,否则按照之前的思路处理,改过之后的代码如下:

#include <iostream>
using namespace std;

int main()
{
   int a,b,c;
   int s[8];
   int i=0;
   cin>>a>>b;
   c=a+b;
   if(c<0){
       cout<<'-';
       c=-c;
   }
   while(c){
    s[i++]=c%10;
    c/=10;
   }
   if(i){
    i-=1;
    while(i){
     cout<<s[i];
     if(i%3==0){
        cout<<',';
     }
     i-=1;
    }
    cout<<s[0]<<endl;
   }else{
       cout<<'0';
   }
}

 

 最后,贴一张通过堆栈得到的实现代码。思路是将结果按字符处理,压入堆栈中,且每压入三个字符,额外压入一个逗号,最后再将堆栈输出即可。

#include<cstdio>
#include<stack>
using namespace std;

int main(){
  int a,b,c;
  scanf("%d%d",&a,&b);
  c=a+b;
  if(c<0){
    printf("-");
    c=-c;
  }
  int k=0;
  stack<char> q;
  while(c/10){
    q.push(c%10+'0');
    k++;
    c/=10;
    if(k%3==0){
      q.push(',');
    }
  }
  q.push(c+'0');
  int len=q.size();
  for(k=0;k<len;k++){
      printf("%c",q.top());
      q.pop();
  }
  return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值