While循环未检查或条件

时间:2019-07-15 07:24:49

标签: c++

我正在做c ++练习。我要解决的一个问题如下...

编写一个程序,继续要求用户输入5以外的任何数字,直到用户输入5。 然后告诉用户“嘿!您不应该输入5!”并退出程序。

★修改程序,以便在10次迭代后,如果用户仍未输入5,则会告诉用户“哇,你耐心得多,我就赢了。”然后退出。

#include <iostream>

using namespace std;

int main()
{
    int userNum;
    int numTimes = 0;

    do
    {
        cout << "Please enter a number: ";
        cin >> userNum;
        numTimes++;

    }while ((numTimes != 10) || (userNum != 5));
    {
        if (numTimes == 10)
        {
            cout << "Wow, you're more patient than I am, you win.\n";
        }
        else
        {
            cout << "Hey! you weren't supposed to enter 5!\n";
        }
    }
}

我似乎无法使while循环的or条件起作用。

3 个答案:

答案 0 :(得分:1)

在此处更改

while ((numTimes != 10) || (userNum != 5));

对此

while ((numTimes != 10) && (userNum != 5));

因为您希望它在一种情况变成false后立即停止。您现在使用||的方式,只有在同时满足两个条件的情况下,它才会停止,因此,如果第十个数字是5。如果仅输入5或到达10,它就不会停止。如果在10个数字之后 输入5,它甚至都不会停止。 / p>

请记住,即使a || btrue中只有一个为真,a仍为b。但是,由于条件混淆了这种方式,为什么不这样分割逻辑呢?

int main()
{
    int userNum;

    for (int numTimes = 0; numTimes < 10; numTimes++){
        std::cout << "Please enter a number: ";
        std::cin >> userNum;

        if (userNum == 5) {
            std::cout << "Hey! you weren't supposed to enter 5!\n";
            return 0;
        }
    }

    std::cout << "Wow, you're more patient than I am, you win.\n";
}

答案 1 :(得分:1)

您正在以一种令人困惑的方式进行操作,我的目标是表达力:

#include <iostream>

int main() {
    int userNum;
    int numTimes = 0;

    while (true) {
        std::cout << "Please enter a number: ";
        std::cin >> userNum;

        if (userNum == 5) {
            std::cout << "Hey! you weren't supposed to enter 5!\n";
            break;
        }

        ++numTimes;

        if (numTimes == 10) {
            std::cout << "Wow, you're more patient than I am, you win.\n";
            break;
        }
    }
}

break使您可以方便地退出循环。但是,请不要“滥用”此代码,以免使其过于复杂或完成怪异的技巧。没有人喜欢spaghetti code

请注意您如何shouldn't use namespace std;。也请尝试在++var上使用var++,因为var++不必要地复制了对象。


Please enter a number: 5
Hey! you weren't supposed to enter 5!

Please enter a number: 12
Please enter a number: 45
Please enter a number: 12
Please enter a number: 0
Please enter a number: 9
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 1
Wow, you're more patient than I am, you win.

答案 2 :(得分:0)

问题在于您的状况。您的循环将继续进行,直到条件不再满足为止。

while ((numTimes != 10) || (userNum != 5));

强制循环继续,直到两个条件都为假。如果您的numTimes == 10,则userNum仍为<5

while ((numTimes < 10) and (userNum != 5));

条件是否正确