3

Input two integers a and b, 1<=a,b<=10^6. Print their sum.

code using int:

int a, b;
cin >> a >> b;
cout << a + b;

code using double:

double a, b;
cin >> a >> b;
cout << a + b;

After I submit these code to the online judge website, the first code can pass all 5 cases, but the second can pass only 3 and the other 2 are wrong answer.

But since double include the range of int, why can't it pass some of the cases that int can? I understand using double instead of int may be a waste of memory, but I think this should not cause any mistake.

Besides, when using double, if I print the result using printf("%.0lf", a + b);,it can also pass all 5 cases.

I know this is an extremely simple program but i can't figure out why it may be wrong using double.

Buqian Zheng
  • 301
  • 4
  • 10
  • Hey, you are either using **C** or **C++** but not both. – Kotshi Oct 21 '15 at 12:10
  • Possible duplicate of [Floating point inaccuracy examples](http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples) – Magisch Oct 21 '15 at 12:12
  • 1
    @Magisch This has nothing to do with floating point accuracy (double-precision floating point can represent all 32-bit integers accurately). – interjay Oct 21 '15 at 12:17
  • @interjay What do you mean "accurately"? `double` can only represent approximate values of all 32-bit integers, I wouldn't necessarily call that "accurate". – Emil Laine Oct 21 '15 at 12:21
  • 3
    [Here's](http://ideone.com/vGUTWo) an example showing how it fails. – interjay Oct 21 '15 at 12:21
  • @zenith You are incorrect. `double` can represent all values of 32-bit ints 100% accurately, without any imprecision. – interjay Oct 21 '15 at 12:22
  • 5
    [Here's a simple example](http://ideone.com/IX57wg) that show the possible differences. You need to use the proper [I/O manipulators](http://en.cppreference.com/w/cpp/io/manip) to format the output correctly. – Some programmer dude Oct 21 '15 at 12:23
  • 2
    The online judge website probably expects to output to be in a specific format, and doesn't accept e.g. scientific notation. – Emil Laine Oct 21 '15 at 12:26
  • @interjay Thank you very much! – Buqian Zheng Oct 21 '15 at 12:28
  • @Joachim Pileborg Thank you very much! – Buqian Zheng Oct 21 '15 at 12:28
  • @zenith you are right. The problem is caused by scientific notation when the result is too large as interjay and Joachim Pileborg show in their example. Thank you very much. – Buqian Zheng Oct 21 '15 at 12:33

1 Answers1

1

When the result is larger than or equal to 10^6, it would be printed by cout in scientific notation which is not accepted by the online judge.

Buqian Zheng
  • 301
  • 4
  • 10
  • 1
    As @Joachim Pileborg pointed out use the IO manipulators to change the format. cout << fixed << setprecision(0) << a + b; Just update as needed as discussed in the link he provided – CJCombrink Oct 21 '15 at 12:49