c++ While循环终止与功能

标签 c++ loops while-loop switch-statement srand

因为它早些时候工作得很好,所以我抓耳挠腮,但是当我去添加一些其他功能时,我的程序突然崩溃了,我无法让它恢复到原来的状态。

类(class)让我编写了一个石头/剪刀布程序来对抗计算机,任何关于为什么循环不断终止自身的帮助都会很棒

#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;
}

最佳答案

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

这相当于

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

这几乎肯定不是您想要的。 'q' 是一个非零的 char 文字,它是“真实的”,因此这个表达式永远不会为假。这类似于编写 if (choice == 'Q' || true)

解决方法是:

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

关于c++ While循环终止与功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43532808/

相关文章:

python - while 循环不会中断,当计数器不再小于数组长度时应该中断

c++ - 从 operator<< 调用纯虚函数

c++ - 为什么虚拟 cudaMalloc 会加速现代GPU中的interval_gather?

javascript - 遍历数组直到找到指定元素的第一次出现?

javascript - 在循环内连接 html 标签

java - 如何在C中读取字符串的第一个字符

r - 在 while 循环中借助 if 语句让 R 跳过某些索引值

python - 当我的 while 循环满足特定条件时,如何结束我的程序?

c++ - token 错误前预期的不合格 ID

c++ - 反转文件中的输入 (C++)