PAT甲级1001 A+B Format (20 分) c++
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 -106≤a,b≤106 . 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
题意:
题目就是输入两个数,然后输出这两个数的和的标准形式,从这个数的后面开始,每三位输出一个‘,’,范围是-1000000~1000000。
做题思路:
字符串的形式接收两个数,用函数stoi()将其转换为int类型求和,再将和用to_string()转换为字符串,然后对其字符逐个判断和输出。
注意点:
①1234的输出格式应该为1,234而不是123,4。
刚开始我是每三次输出逗号,一直没找到这个原因
代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
string a, b;
cin >> a >> b;
string sum = to_string((stoi(a) + stoi(b)));
for (int i = 0; i < sum.length(); i++)
{
cout << sum[i];
if(sum[i]=='-')
continue;
if ((i+1)%3==sum.length()%3&&i!=sum.length()-1)
//字符长度对3求余和当前的长度的余数相等时输出,
//不是每三个数输出,
{
cout << ',';
}
}
return 0;
}