Question 9
Back to Exercise
What is the output of the following C program?
#include <stdio.h>
int main(void) {
int steps = 0;
for (double x = 0.0; x < 1.0; x += 0.1)
steps++;
printf("%d\n", steps);
return 0;
}
- A 10
- B 11 Correct
- C 9
- D It never ends
Correct Answer: Option B
0.1 is slightly off in binary, and after ten additions x is 0.9999999999999999 – still less than 1.0 – so the loop runs an 11th time. Use an integer counter for an exact number of passes.
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!