A1001 A+B Format (20 point(s))

a+b和按要求输出

1. 原文

原题

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 −106a,b106. 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:

1
-1000000 9

Sample output:

1
-999,991

2. 解析

a,b两数相加的和按格式输出

求和结果的位数

1
2
3
4
do{
num[idx++]=sum%10;
sum/=10;
}while(sum!=0);

求得的数组是从个位到最高位排列的199999

从个位开始,cnt=1,循环遍历,每次cnt++表示前进一位,当遍历满三位时ans+=’,’ —>199,

⚠️注意处理最后一位,9前面不加 199,999

最后字符串反向输出 999,991

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<cstdio>
int num[20]={};
int main(){
int a,b;
scanf("%d%d",&a,&b);
int c = a+b;
if (c<0)
{
printf("-");
c = -c;
}
int idx = 0;
do{
num[idx++]=c%10;
c/=10;
}while(c!=0);
for (int i = idx-1; i >= 0; i--)
{
printf("%d",num[i]);
if (i%3==0&&i>0)
{
printf(",");
}
}
printf("\n");

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1001/
  • 发布时间: 2019-09-03 12:36
  • 更新时间: 2021-10-29 13:58
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

Gitalking ...