题目连接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400
Quesetion Describe:
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
题目大意:
求A+B的值,结果按照三位数字一个逗号隔开的格式输出【例:1,000】
思路:
这题是典型的A+B,范围也不大,两者相加最大也不过是int范围,主要是三位一个逗号的格式,需要单独考虑一下最后结果少于四位不要输出逗号了,防止误判。详情可见Code注释。
AC代码:
1 #include <iostream> 2 3 int main() 4 { 5 int a,b; 6 int ch[50]; 7 std::cin >> a >> b; 8 int num =0 ; 9 int c = a+b; //直接相加 10 if(c / 1000 !=0) //判断是否大于等于1000,否则易出现1+1=002 11 { 12 if(c < 0) //负数将其负号去掉,方便操作 13 { 14 std::cout << '-'; 15 c=0-c; 16 } 17 while(c!=0) //将c按照3位3位分开存入数组 18 { 19 ch[++num] = c %1000; 20 c/=1000; 21 } 22 std::cout << ch[num--] ; //先输出首位,防止出现001,200的情况 23 for(int i = num;i>=1;i--) 24 { 25 std::cout<< ','; 26 std::cout.fill('0'); //补位0 27 std::cout.width(3); //限制3位 28 std::cout << ch[i] ; 29 } 30 } 31 else 32 { 33 std::cout << c << std::endl; //小于1000直接输出 34 } 35 36 }