天天看點

《C++遊戲程式設計入門(第4版)》——2.4 使用帶else子句的if語句序列include

本節書摘來自異步社群出版社《c++遊戲程式設計入門(第4版)》一書中的第2章,第2.4節,作者:【美】michael dawson(道森),更多章節内容可以通路雲栖社群“異步社群”公衆号檢視。

c++遊戲程式設計入門(第4版)

我們可以将帶else子句的if語句連接配接起來,建立循序驗證的表達式序列。第一個與驗證為真的表達式關聯的語句将被執行;否則,程式執行與最後的(可選)else子句關聯的語句。下面給出這樣一個序列的形式:

// score rater 3.0

// demonstrates if else-if else suite

using namespace std;

int main()

{

   int score;

   cout << "enter your score: ";

   cin >> score;

   if (score >= 1000)

   {

     cout << "you scored 1000 or more. impressive!n";

   }

   else if (score >= 500)

     cout << "you scored 500 or more. nice.n";

   else if (score >= 250)

     cout << "you scored 250 or more. decent.n";

   else

     cout << "you scored less than 250. nothing to brag about.n";

   return 0;

}<code>`</code>

《C++遊戲程式設計入門(第4版)》——2.4 使用帶else子句的if語句序列include

圖2.4 根據使用者的分數,顯示多條消息中的某一條

我們已經兩次見過該序列的開頭部分,這次它的工作方式還是一樣。如果score大于等于1000,則顯示消息you scored 1000 or more. impressive!,然後程式跳轉到return語句。

  <code>if (score &gt;= 1000)</code>

然而,如果該表達式為false,那麼可以肯定score小于1000,程式計算序列的下一個表達式:

  <code>else if (score &gt;= 500)</code>

如果score大于等于500,則顯示消息you scored 500 or more. nice!,然後程式跳轉到return語句。然而,如果該表達式為false,那麼可以肯定score小于500,程式計算序列的下一個表達式:

 <code>  else if (score &gt;= 250)</code>

如果score大于等于250,則顯示消息you scored 250 or more. decent.,然後程式跳轉到return語句。然而,如果該表達式為false,那麼可以肯定score小于250,程式執行與最後的else子句關聯的語句,顯示消息you scored less than 250. nothing to brag about.。

提示

 雖然最後的else子句在if else-if組合中不是必需的,但我們可以在序列中沒有表達式為真的情況下使用它來執行代碼。

繼續閱讀