编译器错误与 if 条件
Compiler error with if-conditions
如果语句是这样工作的吗?这是一个"猜数字"的游戏。第一个 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)) {
...
}
相关文章:
- 无论条件是否为true,if总是在c++中执行
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 为什么简单的算术减法在"if"条件下不起作用?
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 为什么这个if(s[j]==s[i] && i>0)条件不适用于这个[{()}]
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- C++ 中的"if"语句不会从左到右计算条件
- 当我的 if 条件计算结果为 false 时,我的 else 块将不会执行
- C++ GUI 条件 if 语句始终为真
- 条件if中类成员的作用域
- 将数组成员与嵌套循环进行比较,计算满足条件(if)的次数
- 子句内多个条件"if"求值顺序
- 如何在c++中循环遍历多个条件IF语句
- 紧凑的多条件if语句
- 智能指针作为条件:if (p)和if (p.get())是等价的
- 哪一个更快?函数调用或条件if语句
- 优化条件"if (m == 0 || n == 0)"的方法
- C/C++多条件If语句