为什么我的while循环永远不会结束? C ++

时间:2014-10-07 21:04:57

标签: c++ do-while

int main ()
{

int wordCode;

const int QUIT_MENU = 9;

菜单

do
{
    cout << "Given the phrase:" << endl;
    cout << "Now is the time for all good men to come to the aid of their ___.\n" << endl;
    cout << "Input a 1 if you want the sentence to be finished with party." << endl;
    cout << "Input any other number for the word country.\n" << endl;
    cout << "Please input your choice now." << endl;
    cin  >> wordCode;
    cout << endl;
    writeProverb(wordCode);

while (wordCode >= 1 || wordCode <= 2)
{
        cout << "You have not entered a valid selection." << endl;
        cout << "Please eneter a 1 or a 2." << endl;

    }

    if (wordCode != QUIT_MENU)
    {
        switch (wordCode)
        {
            case 1:
                writeProverb(wordCode);
                break;
            case 2:
                writeProverb(wordCode);
        }
    }

是退出此循环的正确方法吗?

}while (wordCode != QUIT_MENU);

return 0;
}

开始使用void函数来编写谚语。

void writeProverb (int wordCode)
{
 //Fill in the body of the function to accomplish what is described above

if (wordCode == 1)
{
    cout << "Now is the time for all good men to come to the aid of their party." << endl;
}

if (wordCode == 2)
{
    cout << "Now is the time for all good men to come to aid the aid of their country." << endl;
}

}

“您尚未输入有效选择。” “请输入1或2。”

无论选择什么值,上述文字都会不断重复。

4 个答案:

答案 0 :(得分:3)

为什么要这样?

while (wordCode >= 1 || wordCode <= 2)

用户输入:

           wordCode >= 1      wordCode <= 2            
1              True                True            -> True  || True -> True
-1             False               True            -> False || True -> True
2              True                True            -> True  || True -> True
3              True                False           -> True  || False -> True
999999         True                False           -> True  || False -> True
-99999         False               True            -> False || True -> True

无论用户输入什么号码,条件都可以永远不会变错。

答案 1 :(得分:0)

更改

while (wordCode >= 1 || wordCode <= 2)

if (wordCode == 1 || wordCode == 2)

你不希望那个部分循环;外部do/while处理就好了。您只需要输出一次消息。

答案 2 :(得分:0)

要添加到Marc B的答案,我想你想要while (wordCode == 1 || wordCode == 2)

答案 3 :(得分:0)

将“while(wordCode&gt; = 1 || wordCode&lt; = 2)”更改为“while(wordCode&gt; = 1&amp;&amp; wordCode&lt; = 2)”。这应该可以解决你的循环问题。