问题
I'm working on a simple short C++ code and the for loop is looping one more than it have to (developed using code::blocks):
#include <iostream>
using namespace std;
int main() {
int x = 0;
for (x=10; x<20; x++);
cout<<x;
return 0;
}
The out put is 20 but as far as I know it has to be 19.
link for image : https://drive.google.com/file/d/0B9WsVzm6FTagbC1uNHpMZ1p6SW8/edit?usp=sharing
回答1:
x < 20
is the condition that must be met in order to stay inside the loop, which means that you'll only exit the loop when x >= 20
, so when you reach x = 19
you'll still iterate one more time because 19 < 20
.
回答2:
The output is correct. The second statement x<20
defines whether or not the loop will be executed. However, x gets increased to 20, the condition is not met and the loop is not executed. Your code prints the x variable after the for-loop that's why 20 is the correct ouput.
回答3:
The middle part in the foor loop ;x<20; is the loop condition. Meaning it won't execute the x++ again if it is not true any more. Thus the loop will stop only when x reaches 20
回答4:
We can rewrite your code using a while loop, that may make it more clear:
int main() {
int x = 10;
while (x < 20)
x++;
cout << x << "\n";
return 0;
}
When written this way, it is clear that at the iteration when the while loop ends that x == 20
.
来源:https://stackoverflow.com/questions/21958151/for-loop-loops-one-more-time-than-it-have-to