PAT甲级刷题 -- 1001 A+B Format

1001

问题: A+B Foramt

Question:
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

分析考虑!

分析问题:题目要求将求和后的数字添加千分位分隔输出;刚看到这个问题我便想起了python中格式化输出添加千分位的方法,但是这个。。没有这么轻松。C语言中没有直接的方式对数字添加千分位分隔的格式化方法。因此我们只能自己考虑逐个数字的打印并在相应位置上添加分隔符 ‘ , ’ ,以打印字符的方式完成显示。

开始动手!

#include <stdio.h>
#define SIZE 10

int main(void)
{
	int a,b,sum;
	int i = 0,count = 0;
	char arr[SIZE];			//字符数组

	scanf("%d %d",&a,&b);
	sum = a + b;	//	求和

	//处理特殊边界
	if(sum == 0)	
		putchar('0');
	if(sum < 0)		
	{
		putchar('-');
		sum = (-1) * sum;
	}

	//将数字从低位到高位依次保存在字符数组中
	while(sum)
	{
		arr[i++] = sum % 10 + '0';
		count++;
		sum /= 10;
		//每三个数字且还存在下个高位,即sum != 0时,存入','
		if(count % 3 == 0 && sum != 0)
			arr[i++] = ',';
		
	}
	
	//逆序输出,从高位到低位依次输出
	for(i--;i >= 0;i--)
		printf("%c",arr[i]);
	printf("\n");

	return 0;
}

回顾反思!

我踩的第一个坑:企图两三行完成输出。刚开始我一直觉得这就是个很简单的类似于python那种一条语句就可以搞定的题目,但是仔细想来,C语言中没有这么容易的方法实现这一数字分隔,只能通过处理字符串的方式。
我踩的第二个坑:何时需要加入分隔符 ’ , ',如何切片。比如12345,要添加千分位分隔符如果是依次存入数组,每三位输出一个分隔符的话,就成了123,45这并不是我们想要的。

因此重新思考算法,既然是添加千分位分隔符。那我们是不是可以先从低位到高位依次取到相应位的数字存入字符数组,同时如果需要千位分隔符的时候我们添加分隔符到字符数组,最后我们从高位到低位倒序输出就大功告成啦!

原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

发布了18 篇原创文章 · 获赞 4 · 访问量 846

猜你喜欢

转载自blog.csdn.net/GuoningningPro/article/details/103585901