2012-04-27 64 views
0

如果语句以这种方式工作吗?这是一个“猜数字”游戏。第一个如果说更高/更低,第二个如果说你是在50,100或100+范围内。if条件下的编译错误

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

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; 

} 
+1

我也在做代码太复杂,或者这是可读的吗? – Foxic 2012-04-27 04:15:01

+3

你有额外的大括号,其中不明确的点和一些关键丢失的括号。 – geekosaur 2012-04-27 04:15:42

+1

你有什么错误? – iammilind 2012-04-27 04:15:43

回答

4

之前你缺少括号。

例如,该行:

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

改为:

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

由于整个如果条件必须包装在括号中。

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

0

除了正确答案通过@乔纳森 - 木材,下面可以更清晰地表达自己的意图:

#include <cstdlib> 
... 
const int off_by = abs(x - y); 

if (off_by <= 50) { 
    ... 
} else if (off_by <= 100) { 
    ... 
} 

FYI:如果你认为它会提高你的代码的可读性,你也可以使用“或“和”和“而不是”||“和“& &”。所以,以下是合法的:

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