Question 8
Back to Exercise
What is the risk in for (float x = 0.0f; x != 1.0f; x += 0.1f)?
- A None
- B 0.1 is not exact in binary, so x may never equal 1.0 and the loop may never stop Correct
- C float cannot be used in a for loop
- D It runs exactly 10 times on every machine
Correct Answer: Option B
0.1 has no exact binary representation, so the sum drifts and can step over 1.0. Count with an integer and compute the value: for (int k = 0; k <= 10; k++) { float x = k / 10.0f; … }.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!