-7

Can someone pls explain me why this is not printing hello?

int main(){
    float i;
    i=1.2;
    while (i==1.2){
        printf("hello");
}
PRO-STER
  • 1
  • 1
  • It doesn't compile, but 1.2 is a double value and `i` is a float value. 1.2 is not exactly representable as either a float or double, and the two values are not exactly the same. `while (i == 1.2f)` will probably work. – Paul Hankin Aug 12 '21 at 14:30
  • Does this answer your question? [How should I do floating point comparison?](https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison) – Mark Benningfield Aug 12 '21 at 14:31
  • @MarkBenningfield This code *could* work if `i` was `double`, or the constant `1.2` were replaced by `1.2f` in both assignment and comparison – Eugene Sh. Aug 12 '21 at 14:32
  • 1
    Does this answer your question? https://stackoverflow.com/q/1839422/16553790 – susanth29 Aug 12 '21 at 14:32
  • thank you guys it helped solve my problem – PRO-STER Aug 12 '21 at 14:47
  • The first problem with your code is there is not brace after your while loop and what Edwin Buck suggested is also the problem – HiddenSquid123 Aug 12 '21 at 14:34

1 Answers1

1

Computers only store digital information. Integers can be represented accurately in binary, but floating point numbers are approximated.

It seems that in the approximations, additional tiny values are preventing your exact comparison from being true.

Now is a good time to google "what every programmer should know about floating point numbers" and read it. It will save you countless hours of future programming and debugging if you learn it early.

In addition, there are two floating point types "float" and "double". You are comparing a float to a double, so the approximations of the value are likely not the same approximation, creating more of a chance that the two values won't be equal.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138