For each pair of integers A B and C ( -2^31 <= A, B, C<= 2^31-1 ), Output the result of A+B+C on a single line.
Sample Input
1 2 33 4 3
Sample Output
610
提示 请注意32位机上int的表示范围。
—————————————————— 题目如上,看起来很简单的问题
根据提示,我知道简单的用int是不行的 根据1001的示例,写出的程序如下:
#include <iostream> using namespace std; int main() { long a,b,c; while(cin>>a>>b>>c) { cout<<a+b+c<<endl; }
return 0; }
提交的结果是Wrong Answer。
后发现,long>=int 很多情况下,是取等于
所以,用long是不行的。
干脆改为long double,还是wa(Wrong Answer) 仔细研究了数据类型长度
发现32位机子上 type sizeof short 2 int 4 long 4 double 8 long double 12 就是说,题目中A,B,C都可以用int表示,只是结果就超过了int的表示范围。 ---------------------------- 于是,改为
#include <iostream> using namespace std; int main() { int a,b,c; double sum; while(cin>>a>>b>>c) { sum=a+b+c; cout<<sum<<endl; }
return 0; }
结果,还是wa 用A=B=C=2^31-1 即2147483647 测试,结果是用科学计数法表示的,为2.14748e+09 经调试,才发现,原来a+b的值为-2,即已经越界了。 ----------------------------------- 改为:
#include <iostream> using namespace std; int main() { int a,b,c; double sum; while(cin>>a>>b>>c) { sum=(double)a+b+c; cout<<sum<<endl; }
return 0; }
结果,wa 调试,结果是正确的, 那么就是输出结果不符合要求 C++double的默认输出好像是科学计数法的,所以修改为:
include <iostream> #include <iomanip> using namespace std; int main() { int a,b,c; double sum; while(cin>>a>>b>>c) { sum=(double)a+b+c; cout<<fixed<<setprecision(0)<<sum<<endl; }
return 0; }
调整fixed输出,找了很久,才发现fixed是对应于scientfic的,英语还是不行 挑战有效位数,使看起来象整数。
提交,accepted。
才算OK。 ——————————————– 看起来很简单的东西,很多的细节,还是不会注意到,汗! |