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 −10?6??≤a,b≤10?6??. 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 PAT A1001 A+B Format 3 ****************************************************/ 4 #include <iostream> 5 #include <string> 6 7 using namespace std; 8 9 int main() { 10 int num1 = 0, num2 = 0, sum = 0; 11 12 cin >> num1 >> num2; 13 14 sum = num1 + num2; 15 16 if (sum < 0) { 17 cout << ‘-‘; 18 sum *= -1; 19 } 20 21 string sumString = to_string(sum); 22 for (int i = 0; i < sumString.size(); ++i) { 23 cout << sumString[i]; 24 if ((i + 1) % 3 == sumString.size() % 3 && i != sumString.size() - 1) { 25 cout << ‘,‘; 26 } 27 } 28 29 return 0; 30 }
注意事项:
无。
原文地址:https://www.cnblogs.com/mrdragon/p/11412264.html
时间: 2024-10-09 03:18:31