好吧,初学者,放轻松.谢谢.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x = 0;
bool while1 = true;
while (while1)
{
cout << x << "\n";
sleep(200);
if (x < 10)
{
while1 = true;
}
else if (x >= 10)
{
while1 = false;
}
x = x+1;
}
cin.get();
}
Run Code Online (Sandbox Code Playgroud)
好吧,所以我不明白为什么程序甚至得到x到10如果我有if语句检查x <10之前我有1添加到x ...请解释.
运营顺序是:
while1为假)则停止循环while1如果是,则设置为false当x为9时,我们按如下方式进行:
while1是真的)while1为truewhile1是真的)while1为falsewhile1设置为false所以,当它是10时,x会被打印出来.问题是,你检查和操作检查的方式,你在停止之前做了一个循环太多.
解决这个问题的一种方法是
while (x < 10)
{
cout << x << "\n";
Sleep(200);
x = x+1;
}
Run Code Online (Sandbox Code Playgroud)
现在循环不会在相同的传递中执行,x是10,而不是之后的传递.
更好的是:
for (int x = 0; x < 10; ++x)
{
cout << x << "\n";
Sleep(200);
}
Run Code Online (Sandbox Code Playgroud)
关于循环增加x的值的意图更清楚.
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |