1

Our professor gave us the assignment to explain what happens while compiling this while loop in C. The loop should end after 10 repetitions but it does not. The output does not stop at f = 0.0 but outputs negative numbers, can somebody explain to me why this happens.

int main(){
float f = 1.0;
    while (f != 0.0) {
    f = f - 0.1;
    printf("%d\n", f);
    }
}
  • 2
    Do study the duplicate carefully. Briefly here, `0.1` is actually `0.1000000000000000055511151231257827021181583404541015625`. Plus `f - 0.1` is an expression of a `double` type. So `f` becomes negative without ever being exactly zero. The moral of the story is to never use a floating point type as a loop control variable. – Bathsheba Apr 05 '19 at 18:05

0 Answers0