PAT A1001 A+B Format
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 −. 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
题目大意:给定两个数,计算两个数的和并且按照xxx,xxx,xxx这样的格式输出。
解题思路:
(1)计算两数之和。
(2)和是负数就输出一个符号并将和取绝对值,然后将和按位存入int类型数组中。
(3)从高位到低位输出数组中的数据,每隔三位输出一个逗号。
需要注意的点是:和为0的情况不能忽略,还有就是输出注意最后一位不输出逗号。
#include<iostream> using namespace std; int main() { int a, b; cin >> a >> b; int sum = a + b; if (sum < 0) { printf("-"); sum = -sum; } int res[7]; int len = 0;//记录长度 //和为0的情况 if (sum == 0) res[len++] = 0; while (sum) { //将sum按位存储,从低位到高位 res[len++] = sum % 10; sum = sum / 10; } //输出时从高位到低位输出 for (int i = len - 1; i >= 0; i--) { printf("%d", res[i]); //每三位输出一个逗号,最后一位除外 if (i > 0 && i % 3 == 0) printf(","); } cout << endl; system("pause"); return 0; }
唯有热爱方能抵御岁月漫长。