for loop , loops one more time than it have to

徘徊边缘 提交于 2019-12-11 19:16:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!