3

I saw this code on Exam: the question is how many times this string will be printed.

I thought first it will be 10 times but this is wrong. Can someone tell me why my answer is wrong. This is part of a code in the C language.

for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) {
    printf("lbc");
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Elior Sastiel
  • 1,074
  • 2
  • 10
  • 21

2 Answers2

7

Assuming x is a 32 bit floating point:

Floating point values have a limited resolution. 100000001 is 1*10^8 so you lose your 1 at the end. If you would add 1, it again gets lost because the next float value is 1.00000008*10^8. You can add as many 1s as you like the result will always be the same.

That is the reason why your code is an endless loop.

Kami Kaze
  • 2,069
  • 15
  • 27
5
float x = 100000001.0f;

will initialize x with the nearest representable float, which is 100000000. Adding 1 to this value will lead to the same value.

If you print the value of x in the loop you will see what happen: http://ideone.com/3FJGTz

mch
  • 9,424
  • 2
  • 28
  • 42