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).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −≤a,b≤. 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
解题思路:
1、求出和后若是负数先输出负号,然后取和的相反数继续操作
2、逐步提取和的每一个数字,然后倒着输出来
3、设置一个计数的,每到三个就输出逗号,然后再继续输出
注意:
groups of three意指“有三个对象的分组”,而不是“三个分组”
答案代码:
#include<iostream>
using namespace std;
int main()
{
long long a,b,sum; //
int ans[100];
cin >> a >> b; //连续输入两个数据不换行的话中间默认空格
sum = a + b;
if(sum < 0){
cout << '-';
sum = sum * (-1);
}
int cnt = 0,count = 0;
do{
ans[cnt++] = sum % 10;
sum /= 10; //整型数据如果出现小数则只保留整数部分
count++;
if(count % 3 == 0){
ans[cnt++] = -1;
}
}while(sum != 0);
if(ans[cnt-1] == -1){
cnt--;
}
for(int i = cnt - 1; i >= 0; i--){
if(ans[i] == -1){
cout << ',';
}
else{
cout << ans[i];
}
return 0;
}
}
原文链接:https://blog.csdn.net/qq_39562286/article/details/81453865