首页 文章

C While Loop Break [关闭]

提问于
浏览
-2

我的目标是创建一个C程序,重复执行一大块代码,直到用户输入一个适当的值,然后使用while循环 . 我的代码只是一遍又一遍地重复,即使我输入“0”,它仍然会重复循环中的代码块 .

这是我的源代码:

#include <iostream>
using namespace std;

int main()
{
    int num = 0;
    bool repeat = true;
    while (repeat = true)
    {
        cout << "Please select an option." << endl;
        cout << "[1] Continue Program" << endl;
        cout << "[0] Terminate Program" << endl;
        cout << "---------------------" << endl;

        repeat = false;

        cin >> num;
        cout << endl;

        if (num = 1)
        {
            repeat = true;
            //execute program
        }
        else if (num = 0)
            repeat = false;
        else
            cout << "Please enter an appropriate value.";
    }

    return 0;

}

3 回答

  • 2
    while (repeat = true)
    

    while 条件中,您使用赋值运算符 = ,而不是相等 == .

    它是有效的C语法,但不是您所期望的 . repeat 被分配给 true ,因此条件始终为true .

    if (num = 1)else if (num = 0) 中存在相同的错误 .

  • 1
    while (repeat = true)
                    ^^
    

    是你的一个问题:

    while (repeat == true)
                    ^^
    

    通过赋值,条件始终求值为true .

    有些人主张使用 Yoda condition 来避免这些错别字 . 另一种方法是简单地编译具有最高警告级别的程序:

    -Wall
    
  • 2

    检查您的操作员 . 您在while和if参数中使用赋值运算符 = 而不是比较运算符 == .

相关问题