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
思路:
这道题大概是说,a+b之后输出sum
sum的格式要按银行账户的金额格式来
每隔3位有一个逗号
没啥思路不思路的,再一次印证了 / 和 %的作用
尝试AC
(一)
using namespace std;
#include<iostream>
#include<cmath>
int main() {
int a(0),b(0);
int sum(0);
cin>>a>>b;
if(a>=-10^6 && a<=10^6 && b>=-10^6 && b<=10^6){
sum=a+b;
}
if(a*b<0){
sum=abs(sum);
cout<<'-'<<sum/(10^3)<<','<<sum%(10^3)<<endl;
}
else
cout<<sum/1000<<','<<sum%1000<<endl;
return 0;
}
答案一直错,后来实验表明
是line 14里cout的 10^3要把它算出来
如line 17所示
(二)
using namespace std;
#include<iostream>
#include<cmath>
int main() {
int a(0),b(0);
int sum(0);
cin>>a>>b;
if(a>=-10^6 && a<=10^6 && b>=-10^6 && b<=10^6){
sum=a+b;
}
if(a*b<0){
sum=abs(sum);
cout<<'-'<<sum/1000<<','<<sum%1000<<endl;
}
else
cout<<sum/1000<<','<<sum%1000<<endl;
return 0;
}
只过了两个测试点,提示还是数字格式的问题
(三)
更改了数字格式问题
提示我非法数字入侵问题
emmm…改一下
把没必要的条件去掉
后来报错说我没把所有可能条件罗列出来
所以改了一下输出的条件句
(四)
using namespace std;
#include<iostream>
#include<cmath>
int main() {
int a(0),b(0);
int sum(0);
cin>>a>>b;
// if(a>=-1000000 && a<=1000000 && b>=-1000000 && b<=1000000){
// sum=a+b;
// }else
// return 0;
sum=a+b;
if(sum<0){
sum=abs(sum);
cout<<'-'<<sum/1000<<','<<sum%1000<<endl;
}
else if(sum==0)
cout<<0<<endl;
else
cout<<sum/1000<<','<<sum%1000<<endl;
return 0;
}
真好,又多了一分…
(原本静待AC的我 =-= )
无提示状态下自省
真好诶,又加了个else分支
多赚了2分
我感觉我像个屎壳郎
正在一点点慢慢把分数往窝里搬…
dbq,我不该把分数比作屎hhh
sum=a+b;
int sum_abs=abs(sum);
if(sum_abs<1000)
cout<<sum<<endl;
if(sum_abs>1000 && sum_abs<1000000 && sum>0)
cout<<sum/1000<<','<<sum%1000<<endl;
if(sum_abs>1000 && sum_abs<1000000 && sum<0)
cout<<sum/1000<<','<<-sum%1000<<endl;
if(sum_abs>1000000 && sum>0)
cout<<sum/1000000<<','<<sum%1000000/1000<<','<<sum%1000<<endl;
if(sum_abs>1000000 && sum<0)
cout<<sum/1000000<<','<<-sum%1000000/1000<<','<<-sum%1000<<endl;
还有最后5分!!依旧是没有提示
还带来回震荡的
就因为多加了一个if分支,少了两分??
(五)
好的,想明白了
比如结果是 1,000,000
这时,中间的0需要另外填充
这种情况下,引入#include<cstdio>就很方便地能控制输出格式
%03d
3位int,不足位填充0
代码就直接借鉴了别人的,也不重新敲了
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int c=a+b;
if(c<0){cout<<'-';c=-c;}
if(c>=1000000){
printf("%d,%03d,%03d",c/1000000,c%1000000/1000,c%1000);
}else if(c>=1000){
printf("%d,%03d",c/1000,c%1000);
}else{
printf("%d",c);
}
return 0;
}
总结:
①逻辑缜密性要加强
②输出格式的细节要更好地把控一下