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 −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

 题目分析:

计算两个整数的和,并且这两个整数范围很正常,不大于10^6,

有一点需要注意的是输出需要用题目要求的格式(每3位用逗号分割),可以使用字符串转换把a,b的和转换成字符串,然后对字符串进行操作。

 

#include<iostream>
#include<string>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
string s = to_string(a + b);
int len = s.length();
for (int i = 0; i < len; i++)
{
cout<<s[i];
if (s[i] == '-') continue;
if ((i + 1) % 3 == len % 3 && i != len - 1)
cout << ',';
}
return 0;
}

关键语句:

if ((i + 1) % 3 == len % 3 && i != len - 1) 

i != len - 1 很好理解,就是对最后一位的判断。

((i + 1) % 3 == len % 3 就是在找逗号的位置,i从0开始,所以i+1,因为输出是从前往后输出,索引要用 len%3 找逗号的位置。

比如12,345 ;   12,345,678