1001 A+B Format (20 分)

mac2022-06-30  115

1001 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 −1000000​​ ≤a,b≤10 ​00000​​ . 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的和,然后以每三位数加一个“ ,”的格式输出~ 我第一次写的代码:大概思路是将最后三位取出,先输出前面,再输出逗号和后三位。

#include<bits/stdc++.h> using namespace std; int main() { int a,b,c; cin >> a >> b; c = a + b; if (c/1000!=0) { double d = c%1000; int e = (c-d)/1000; double f = fabs(d); printf("%d,%.0f",e,f); } else cout << c << endl; return 0; }

but…一定有一些情况我没有想到叭!

于是试了下面这组数,发现了问题

于是对输出进行了修改,如下:

#include<bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b; c=a+b; if(c/1000!=0) { double d=c%1000; int e=(c-d)/1000; double f=fabs(d); printf("%d,.0f",e,f); } else cout << c << endl; return 0; }

发现还是部分正确,后来想到七位数时需要写成 x,xxx,xxx

#include<bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b; c=a+b; if(c/1000!=0&&c/1000000==0) { double d=c%1000; int e=(c-d)/1000; double f=fabs(d); printf("%d,.0f",e,f); } else if (c/1000000!=0) {//c=-1234567 double d=c%1000;//567 double f=fabs(d); double g=c%1000000;//234567 int h=(g-d)/1000;//234 int e=c/1000000;//1 double i=fabs(h); printf("%d,.0f,.0f",e,i,f); } else cout << c << endl; return 0; }

最新回复(0)