如果输入不等于x OR x OR x ORx,则得到该点.[C++]

If input does not equal x OR x OR x OR x, you get the point. [C++]

本文关键字:OR C++ 不等于 输入 ORx 如果      更新时间:2023-10-16

我遇到了一些小数字生成器问题。一切都按它应该的方式进行,但我只是在修复错误。我对编码还很陌生,两周前才开始,所以请原谅我缺乏知识。

这是我的代码:

cout << "nnPlease enter a number for one of the following:" << endl;
cout << "1: Completely random number generator (no specified limit)" << endl;
cout << "2: Number generated from x to x, you decide" << endl;
cout << "3: Number generated from 1 to 100" << endl;
cout << "4: Number generated from 1 to 10" << endl;
cout << "5: Random number generated with decimalnn" << endl;
int menuSelection;
cin >> menuSelection;
system("cls");
if (menuSelection != 1||2||3||4||5 ) // my problem lies here
{
    cout << "Please enter a valid selection from 1 to 5!" << endl;
    goto mainMenu;
}

基本上,我希望我的程序不会在有人厚颜无耻地输入非整数的东西时出错和崩溃,并输出错误。

而不是

if (menuSelection != 1||2||3||4||5 )

写比较简单

if (menuSelection <  1 || menuSelection > 5 )

对于这个表达式

menuSelection != 1||2||3||4||5

则使用所谓的相等运算符CCD_ 1和逻辑OR运算符||

与相等运算符的优先级相比,最后一个具有较低的优先级。所以这个表达式看起来像

( menuSelection != 1 )||2||3||4||5

括号中的子表达式产生布尔值truefalse。然后,它的结果被用于带有运算符||和操作数2的子表达式中。非零整数隐式转换为布尔true

所以实际上你有

( menuSelection != 1 )|| true || true || true ||true

不考虑比较CCD_ 6将总是产生CCD_

更正确的表达式看起来像

menuSelection != 1 || menuSelection != 2 || menuSelection != 3 || menuSelection != 4 || menuSelection != 5

但是在程序的上下文中,即使是这个表达式也是错误的。您必须使用逻辑AND运算符&&,而不是对数OR运算符||

menuSelection != 1 && menuSelection != 2 && menuSelection != 3 && menuSelection != 4 && menuSelection != 5

实际上,您想要实现的条件如下:

if (menuSelection != 1 && menuSelection != 2 && menuSelection != 3 && menuSelection != 4 && menuSelection != 5) // my problem lies here
{
    cout << "Please enter a valid selection from 1 to 5!" << endl;
    goto mainMenu;
}

然而,这并不方便。由于!=0是一个整数,您可以简单地将其进行比较:

if (menuSelection < 1 || menuSelection > 5) {
    cout << "Please enter a valid selection from 1 to 5!" << endl;
    goto mainMenu;
}

最后,我想说:goto?求你了,不要。这不是实现好的C++应用程序的方法。

你可以很容易地用这样的东西来代替它:

cout << "nnPlease enter a number for one of the following:" << endl;
cout << "1: Completely random number generator (no specified limit)" << endl;
cout << "2: Number generated from x to x, you decide" << endl;
cout << "3: Number generated from 1 to 100" << endl;
cout << "4: Number generated from 1 to 10" << endl;
cout << "5: Random number generated with decimalnn" << endl;
int menuSelection;
cin >> menuSelection;
while (menuSelection < 1 || menuSelection > 5)
{
    cout << "Please enter a valid selection from 1 to 5!" << endl;
    cin >> menuSelection;
}
// Here, menuSelection is definitely between 1 and 5 inclusively

你可以阅读很多关于这个主题的信息。例如,在StackOverflow:
';转到';这不好吗?

我通过将menuSelection更改为字符串解决了最初的问题。再次,我为我缺乏知识而道歉,我正在尽我所能。感谢大家的友好投入。