5

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?

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

9

This is gcc bug #323 , in reality this is not a bug but an implementation detail.

Comments

4

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); 

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.