C++ 而函数不';我不能像我希望的那样工作

C++ 而函数不';我不能像我希望的那样工作,c++,while-loop,C++,While Loop,while函数出现新问题。虽然听起来很简单,但我还是无法控制自己 像我的上一个程序一样,这个程序在收到正确和错误的消息后意外关闭。 我想在输入一个数字后循环这个,这样程序就不会停止。 谢谢你的帮助,如果有的话 #include <iostream> using namespace std; int main() { int X = 0; //setting the first variable int num; //setting the second w

while函数出现新问题。虽然听起来很简单,但我还是无法控制自己

像我的上一个程序一样,这个程序在收到正确和错误的消息后意外关闭。 我想在输入一个数字后循环这个,这样程序就不会停止。 谢谢你的帮助,如果有的话

#include <iostream>
using namespace std;

int main()
{
    int X = 0; //setting the first variable
    int num; //setting the second

    while (X == 0) //this should happen whenever X is equal to 0
    {
          cout << "Type a number bigger than 3. "; //output
          X++; //This should increase X, so that the next while function can happen
    }
    while (X == 1) //again, since I increased x by one, (0+1=1 obviously) this should happen
    {
          cin >> num; //standard input
          if (num > 3) //if function: if num is bigger than three, then this should happen
          {
                  cout << "Correct! Try again!" <<endl; //output
                  X--; //Here I'm decreasing x by one, since it was 1 before, now it becomes 0. This should make the "while (X == 0)" part happen again, so that another number bigger than three can be entered
          }
                    if (num <= 3) //if function: if num is lesser than or equal to 3, this should happen
          {
                  cout << "Wrong! Try again!" <<endl; //output
                  X--; //This is supposed to work like the "X--;" before, repeating the code from "while (X==0)"
          }
    }
}
#包括
使用名称空间std;
int main()
{
int X=0;//设置第一个变量
int num;//设置第二个
while(X==0)//这应该在X等于0时发生
{
cout>num;//标准输入
if(num>3)//if函数:如果num大于3,则应该发生这种情况
{

您是否希望将所有代码包装在它自己的
中,而
循环:

while (true /* or something */)
{
    while (X == 0) //this should happen whenever X is equal to 0
    {
    // ...
}
现在它变为0。这将使“while(X==0)”部分再次出现

不。在程序执行过程中,While循环在任何时候都不会神奇地生效。只有当您从上面的代码到达While循环时,您才能进入它。通常,程序是自上而下执行的


如果您想继续循环,您需要在整个程序中循环。您现在拥有的
while
s应该是
if
s。

将两个
while
循环合并为一个,
while(true)

将前面的每个
while
正文置于
if
状态,其中包含旧
while
中的子句

while(true) {
  if (X==0) {
    // the X==0- case
  } else if (X==1) {
    // the X==1 case
  }
}
要结束循环,请执行
中断;

你必须把C++程序看成是一系列指令,比如一个配方。<>代码> 只是一个循环:你检查条件。如果是真的,你运行这个身体。在运行该体之后,你检查“强”>只有“<强”>条件,并运行该体,如果是真的。他

,而
(它后面的
{}
包含了代码),您结束循环并继续下一个循环

第一个循环运行、完成,然后第二个循环在代码中运行。一旦第一个循环退出,就不会因为条件变为真而返回到它

理解流控制是学习编程的“困难”步骤之一,因此,如果您觉得这很棘手,也可以

除了使代码正常工作之外,您还可以对代码进行许多改进—实际上,几乎不需要
X
。但这是一个小步骤!一旦代码正常工作,您可以考虑“如何删除变量
X
?”


在对您的程序进行此类根本性更改之前,您应该让它工作,并保存一份副本,以便“返回”到上一个工作版本。

至少将第二个while循环放在第一个while循环中,以使其按预期工作。否则,您的程序没有理由再次返回


尽管如此,这不是一个好的设计。

使用嵌套的while循环?无论输入和返回0在哪里,都可以修改X;?我建议您使用调试器逐步检查此代码,以便能够准确地看到发生了什么。为什么在这里使用循环?每个循环都在内部确保它只能执行oncE