【问题标题】:Compiler error with if-conditions带有 if 条件的编译器错误
【发布时间】:2014-11-11 19:29:10
【问题描述】:

if 语句可以这样工作吗?这是一个“猜数字”的游戏。第一个 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 number\n";

    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;

}

【问题讨论】:

  • 也是我让代码太复杂还是可读性强?
  • 您有多余的大括号,其点不清楚,并且一些关键的括号缺失。
  • 第 37 行在 '| 之前出现意外的主表达式|'令牌第 38 行应为 ';' before 'cout' 第 39 行 '| 之前的意外主表达式|'令牌第 40 行应为 ';'在'cout'之前

标签: c++


【解决方案1】:

您缺少括号。

例如,这一行:

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

应阅读:

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

因为整个 if 条件必须用括号括起来。

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

【讨论】:

    【解决方案2】:

    除了@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)) {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-23
      • 1970-01-01
      • 2014-08-10
      • 2013-01-11
      • 1970-01-01
      • 2021-06-18
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多