2015-05-19 140 views
-5

無法得到這個工作......路障....幫助?!?我是新手,正在嘗試在Delco CC上爲C++課程編寫遊戲代碼。任何幫助將不勝感激。當它運行時,它不會像循序漸進一樣循環,因此我無法繼續編碼我的遊戲其餘部分。我工作在這個C++代碼上,不能讓它工作......看下面

#include<iostream> 
#include<string> 

using namespace std; 

int findMap() 
{ 
int space; 
cout<<"| 1 | 2 | 3 |"<<endl; 
cout<<"|_____|_____|_____|"<<endl; 
cout<<"| 4 | 5 | 6 |"<<endl; 
cout<<"|_____|_____|_____|"<<endl; 
cout<<"| 7 | 8 | 9 |"<<endl; 
cout<<"|  |  |  |"<<endl; 

cout<<"What space is your map in?"<<endl; 
cin>> space; 
if (space == 4||8) 
{ 
      cout<<"Nope! There's nothing in here."<<endl; 
      return findMap; 
      } 
if (space == 5||6) 
{ 
      cout<<"Tough luck, you only found blank map paper. It's 
useless."<<endl 
      return findMap; 
      } 
if (space == 1||7) 
{ 
      cout<<"You found poision gas. You failed."<<endl; 
      return 0; 
      } 
if (space == 1) 
{ 
      cout<<"Yippie! You found your map!"<<endl; 
      } 
if (space == 9) 
{ 
      cout<<"Well, you found your wallet..."<<endl; 
      return findMap; 
      } 


} 

int game(findMap) 
{ 
string name; 
int findMap; 
cout<<"It appears that you have been lost at sea."<<endl; 
cout<<"But don't worry, you'll only have to survive until you reach 
land, for this round."<<endl; 
cout<<"Anyways, why don't you tell me your name?"<<endl; 
cin>> name; 
cout<<"Well, "<< name<<", do yourself a favour and find your 
map..."<<endl; 
cout<<findMap<<endl; 
} 
+6

我沒有看到代碼中的任何一個循環。請發佈[SSCCE](http://sscce.org) – NathanOliver

+1

現在我看到你正試圖調用findMap - 你沒有正確調用它。這是否編譯了很多警告?如果是,請閱讀。 –

+1

你的問題是什麼? –

回答

2

這樣的經典缺陷錯字

邏輯OR被指定爲:

if ((space == 1) || (space ==7)) 

這與評估語義的順序做。

編輯1:爲什麼你的版本不正確
工作在表達:

(space == 1 || 7) 

短語首先計算爲一個真正的狀態。現在
的表達式是:

(space == true) 

標識符true具有類型bool,因此它被轉換爲相同的類型space,這是inttrueint表示是1
代給我們:

(space == 1) 

你是一種幸運有這一個,但對於7的情況不存在。您所有的if語句都以相同的方式進行評估。

+2

它比評估的順序更多地與語義相關。 –

+1

而且它不是一個錯字,= vs ==會是一個錯字。 – Borgleader

+0

合併建議的評論。 –

1

這是C++中常見的誤解。或(||)運算符通常用於布爾值。因此,當你檢查(space == 1||7)它首先評估space == 1,如果且僅當空間等於1,則評估爲真。然後,在評估(space == 1)之後,它將或運算符應用於7.因爲7總是計算爲真(space == 1||7)總是計算爲真,因爲或者如果表達式中的任何部分評估爲真,則運算符評估爲真。

你想要的是(space == 1 || space == 7),因爲它會評估第一,那麼第二次表達(即space == 1,然後space == 7)和當且僅當其中一方的評價爲true返回true。