PAT 甲级 A1001

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).

输入格式

Each input file contains one test case. Each case contains a pair of integers a and b where − 1 0 6 10^{6} ≤a,b≤ 1 0 6 10^{6} . The numbers are separated by a space.

输出格式

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

总结

  1. 题意大概是给出2个数,然你按照题目给的格式输出。由于a和b的不大,因此不会超界,所以我用了一个非常好理解的方法来解这个题
  2. 设a+b=n,先要做个预处理,若n小于0则输出负号,然后再取相反数;若正数啥也不干。然后就得到n是一个0-2000000的数,分没有逗号,一个逗号和两个逗号三种情况输出,直接进行判断就OK了~注意高位补0

AC代码

#include<iostream>
using namespace std;
int main() {
	int a, b, n;
	scanf("%d %d", &a, &b);
	n = a + b;
	if (n < 0) {
		printf("-");
		n = -n;
	}
	if (n < 1000)  printf("%d",n);
	else if ( n>=1000&&n<1000000) {  //只有一个逗号
		printf("%d,%03d", n/1000,n%1000);
	}
	else { //两个逗号
		printf("%d,%03d,%03d", n / 1000000, n / 1000 % 1000, n % 1000);
	}
	return 0;
}
发布了16 篇原创文章 · 获赞 0 · 访问量 355

猜你喜欢

转载自blog.csdn.net/qq_38507937/article/details/104326687