Problem: Given a real number in exactly two digits after the decimal point, and another integer. Print their product, rounded down to the nearest integer.
You may start to code this way:
double a; int b; cin >> a >> b; int c = a * b; cout << c << endl;
Do you think this is correct? Well, almost. Now, try this input:
What will the output be?
You pick a calculator and it says “8178”. If you also answer “8178” to this problem, then you are wrong.
Why? Because the multiplication is not done in exact; there will be a slight error. If you print (a * b) in fifteen digits after the decimal point, you will likely get this output:
This annoying pitfall happened to me in Codeforces Beta Round #81, Problem A. This problem was supposed to be the easiest problem in the set, however, there were only about one fourth of the solutions passing the system test. Almost all failed solutions got hacked with this rounding error case.
So, the solution is either to parse manually the two digits after the decimal point, or add an epsilon (a very small value) to the result:
double a; int b; cin >> a >> b; int c = a * b + 1e-8; // epsilon = 10^-8 cout << c << endl;
And you will get the correct result.
So, as the title says: add an epsilon before casting doubles to integers.
As a programmer, this is important to know. Has this case ever happened to you? If yes, do you have a more elegant solution?