Reputation: 51
I have the following C program
double d = 1.4;
int x;
x = d * 10;
printf("\n\n VALUE = %d " ,x);
I have gcc 4.3.3 which comes with Ubuntu 9.04
I get answer as 13 with -O0 but get correct answer i.e 14 with higher levels of optimization
Is this a known issue or something wrong with my code?
Upvotes: 5
Views: 400
Reputation: 12298
What Every Computer Scientist Should Know About Floating-Point Arithmetic
It really is what the title says, and it also applies to programmers in general.
Upvotes: 2
Reputation: 47572
This is gcc bug #323 , in reality this is not a bug but an implementation detail.
Upvotes: 9
Reputation: 75389
At higher levels of optimization, GCC probably optimizes both variables away and precomputes the value to print. At no optimization, the value of d
(and thus the printing value) will be subject to floating point representation, and may not be exactly 1.4
. Try this:
double d = 1.4;
int x;
x = d * 10;
printf("Old = %lf, New = %d\n", d, x);
Upvotes: 4
Reputation: 1172
You can't represent 1.4 exactly using double
, the value is actually a bit lagrer or a bit smaller (see this). So there is no "correct" answer - use round()
instead of implictly truncating.
Upvotes: 9