C++函数的While循环终止

4

我正在为此感到困惑,因为早些时候它还能正常工作,但当我尝试添加一些其他功能时,程序突然失控了,而且我无法将其恢复到原来的状态。

我的课程要求我编写一个石头/剪刀/布游戏程序与计算机对战,希望能得到有关循环为什么不断终止的帮助。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;


void RPSout(char);
int RPScomp();

int main() {

    char choice;
    int endit=0;

    while (endit == 0)
    {
        cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
        cin >> choice;

        RPSout(choice);

        if (choice=='Q'||'q')
            {endit=1;}
    }
    return 0;
}


void RPSout(char choose)
{
    int RPS =0;
    int comp=0;
    switch (choose)
    {
    case 'R':
    case 'r':
    {
        cout <<"Your choice: Rock";
        break;
    }
    case 'P':
    case 'p':
    {
        cout <<"Your choice: Paper";
        break;
    }

    case 'S':
    case 's':
    {
        cout << "Your choice: Scissors";
        break;
    }

    case 'Q':
    case 'q':
    {
        cout << "Bye Bye Bye";
        break;
    }

    default:
        cout<<"You enter nothing!"<<endl;
        cout << "The valid choices are R/P/S/Q)";
    }
    return;
}

int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
    unsigned seed = time(0);

    srand(seed);

    comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
    return comp;
}

1
(choice=='Q'||'q') 总是为 true。你需要写成 if (choice=='Q'|| choice=='q') - songyuanyao
4个回答

5
if (choice=='Q'||'q')

这相当于
if ((choice == 'Q') || 'q')

这几乎肯定不是你想要的。 'q' 是一个非零的 char 字面值,因此这个表达式永远不会为假。这就像写 if (choice == 'Q' || true)

解决方法是:

if (choice=='Q' || choice=='q')

2

这个声明

if (choice=='Q'||'q')

始终测试为真,因此将设置您的标志以终止循环。

尝试:

if (choice=='Q'||choice=='q')

1
我认为你的if语句应该是if (choice == 'Q' || choice == 'q')

0

你的问题在于 if 语句

if (choice=='Q'||'q')
        {endit=1;}

|| 'q' 部分始终为真,因为 ASCII 中的 'q' 不为 0,请更改您的代码为

if (choice=='Q'|| choice=='q')
        {endit=1;}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接