2
#include <stdio.h> int main() { float a = 0.7; int c; c = a < 0.7; printf("%d", c); } 

Output printed is 1 though it is printing 0 for all cases except 0.7,7.7 and 0.9, why it is so??? Also it should be 0 because precedence of '<' operator is more than '=' operator

9
  • 10
    I think it is that time of the day again. The obligatory link: What Every Computer Scientist Should Know About Floating-Point Arithmetic Commented Sep 20, 2013 at 9:18
  • @ppeterka66 So 0.7 < 0.7 is supposed to be true? I haven't touched C in many years but that's one funny behaviour alright. Commented Sep 20, 2013 at 9:21
  • You write 0.7 but it can store only 0.699999 or 0.7000001 in a float. Because it can not be exactly represented. Commented Sep 20, 2013 at 9:22
  • Sure but wouldn't you think that 0.7 should always be stored the same way and not randomly? That's what I mean by funny. Commented Sep 20, 2013 at 9:23
  • Take a deep breath, think, remove additional question marks and write a decent question which you could also present your teacher. Your current question is basically worthless: for example "except 0.7, 7.7"? Where do you actually use 0.7? Other than that, ppeterka's link will contain the answer. Probably. Commented Sep 20, 2013 at 9:24

2 Answers 2

13

0.7 cannot be represented exactly as a float value, so a stores some approximation of it. The gotcha here is that the literal 0.7 has type double, so a more precise approximation of 0.7 is used to represent it. That approximation may differ from the less precise one in either direction.

To fix, use a double variable, or a float literal 0.7f.

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

Comments

0

Your basically dealing with the fact that 0.1 is a repeating decimal in binary. So things that look nice and clean as literals (i.e. 0.7) can't be represented exactly. Coupled with this you're mixing types since the literal 0.7 is a double.

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.