编译器错误与 if 条件

Compiler error with if-conditions

本文关键字:条件 if 错误 编译器      更新时间:2023-10-16

如果语句是这样工作的吗?这是一个"猜数字"的游戏。第一个 if 表示要更高/更低,第二个 if 表示您是否在 50、100 或 100+ 范围内。

两者都应该同时工作,但我得到一个错误。

第 37 行 "|"标记之前的意外主表达式,第 38 行 在"cout"之前应为";"

#include <iostream>
#include <cstdlib>
#include <time.h>
#include <cstdio>
using namespace std;
int main()
{
    int x;
    cout << "Please enter a numbern";
    srand(time(0));
    int y = rand();
    while (x != y)
    {
        cin >> x;
        {
        if (!(cin.good()))            //1st if
        {
           cout << "No letters noob" << endl;
           cin.clear();
           cin.sync();
        }
        else if (x < y)
           cout << "Go higher" << endl;
        else if (x > y)
           cout << "Go lower" << endl;
        else
           cout << "You win!!" << endl;
        }
        {
        if (y - x - 50 <= 0) || (x - y - 50 <= 0)        //2nd if
           cout << "within 50 range" << endl;
        else if (y - x - 100 <= 0) || (x - y - 100 <= 0)
           cout << "within 100 range" << endl;
        else
           cout << "100+ value away" << endl;
        }
    }
cin.get();
getchar();
return 0;
}

您缺少括号。

例如,此行:

if (y - x - 50 <= 0) || (x - y - 50 <= 0) 

应为:

if ((y - x - 50 <= 0) || (x - y - 50 <= 0)) 

因为整个 if 条件必须括在括号中。

看起来您可能还有其他一些问题。

除了 @jonathan-wood 的正确答案外,以下内容可能会更清楚地表达您的意图:

#include <cstdlib>
...
const int off_by = abs(x - y);
if (off_by <= 50) {
    ...
} else if (off_by <= 100) {
    ...
}

仅供参考:如果您认为这会提高代码的可读性,您还可以使用"or"和"and"而不是"||"和"&&"。因此,以下内容是合法的:

if ((y - x - 50 <= 0) or (x - y - 50 <= 0)) {
    ...
}