-5

I anticipated it would produce:

10 5 3 2 1

but instead it prints

10 5 3 2 1 1 1 1 1 1 1 1 1...

Why?

#include <stdio.h>

int main(void)
{
    int i;

    for(i = 10; i >= 1; i /= 2)
        printf("%d ", i++);

    return 0;
}

2 is printed, then one is added making it 3, divided by 2 is 1. As 1 is equal to 1, 1 is printed and then one is added making it 2, divided by 2 is 0. As 0 is less than 1, the loop should end.

4

3 回答 3

2

When i is 1, you print it with the printf statement. Then i gets incremented (via the ++ operator in your printf statement). Then i /= 2 is performed, which results to i = 2 / 2 which results to 1. This satisfies your condition i >= 1, making it an infinite loop.

于 2015-03-04T02:51:38.733 回答
1

When i /= 2 becomes 1 then body of the loop will print 1 and increment i by 1. This will never let the value of i /= 2 less than 1 and hence the value of i and the loop will iterate infinitely.

于 2015-03-04T02:52:42.983 回答
1

i keeps getting incremented to 2 and divided by 2 which produces the infinite loop.

于 2015-03-04T03:44:34.693 回答