【问题标题】:important solution for a while loop [duplicate]while循环的重要解决方案[重复]
【发布时间】:2015-11-10 02:48:03
【问题描述】:

各位,为什么这段代码会变成无限循环?我正在学习 C++,所以如果你能解释解决方案,对我来说非常重要!

// Odd_or_Even.cpp : This program determinate if a number is Odd or Even
//

#include "stdafx.h"
#include "std_lib_facilities.h";


int main()
{
    int num = 0;
    bool repeat = true;

    while (repeat == true)
    {
        cout << "Please enter an integer to determinate if it's odd or even: ";
        cin >> num;
        cout << "\nReading data...";

        if (!cin) {
            cout << "Failed\n";
            cout << "There is some problem with the number, sorry!\n";
            cout << "\n";
            cin.clear();
        }
        else
        {
        cout << "God job, now stop lose time.";
        repeat = false;
        }


    }

    keep_window_open();
    return 0;
}

谢谢!

编辑:好的,我写了 if for 阻止循环,但是如果你尝试写一个字母,而不是一个数字,它仍然会进入一个循环!

【问题讨论】:

  • 你应该有一行将在 if 语句中将 repeat 的值更改为 false
  • 是的,我知道,但我希望当我说“对不起”时它会回到顶部并重复,而不是输出变为无限:cout
  • 如果回到开始提示另一个值,你建议什么时候结束循环?
  • @RavenJe 有可用的else子句,您可以在哪里设置repeat = false;?这是什么愚蠢的问题?
  • @RavenJe 好的,至于您的编辑,您需要致电cin.clear() 处理失败案例,以便能够再次获得输入。

标签: c++ loops while-loop infinite-loop repeat


【解决方案1】:

这是一个无限循环,因为您永远不会重复更新。您的 while 循环将继续运行,直到 repeat 设置为 0 或 false。

附:因为repeat是一个布尔值,所以while(repeat)和while(repeat==true)是一样的

【讨论】:

    【解决方案2】:

    您的代码将 repeat 设置为 true,然后您的 while 循环运行 while

    while(repeat == true)

    要使其脱离无限循环,您需要在 while 循环内的某处执行此操作:

    重复=假;

    您希望在什么条件下跳出循环?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      相关资源
      最近更新 更多