2016-10-21 59 views
1

嗨,我正在做一個任務,並有這個程序的一塊麻煩。c + +程序不會退出循環void()函數

「23」的遊戲是一個雙人遊戲,從一堆23個牙籤開始。玩家輪流,一次抽出1根,2根或3根牙籤。退出最後一根牙籤的玩家失去了比賽。寫一個播放「23」的人類與電腦程序。人應該總是先行。當它是電腦的回合,就應該按照以下規則行事:

  • 退出4 - X牙籤,其中X是牙籤人上一轉撤回的數量。

  • 如果有剩餘,則計算機應該收回足夠的牙籤離開1

  • 如果還剩下一個牙籤2至4牙籤,然後,計算機必須把它和它失去。

當玩家輸入要退出的牙籤的數量時,程序應該執行輸入驗證。確保輸入的數字在1到3之間,並且玩家沒有試圖提取比堆中更多的牙籤。

這是我的代碼。任何幫助將不勝感激。

#include <iostream> 
using namespace std; 

void compAlgorithm(int totalTp, int compTp, int userTp, int countr) { 
do { 
    if (totalTp > 4) { 
     compTp = 4 - userTp; 
     totalTp += totalTp - compTp; 
     countr--; 
    } 
    if (totalTp >= 2 && totalTp <= 4) { 
     switch (totalTp) { 
      case 2: 
       totalTp += totalTp - 1; 
       countr--; 
       break; 
      case 3: 
       totalTp += totalTp - 2; 
       countr--; 
       break; 
      case 4: 
       totalTp += totalTp - 3; 
       countr--; 
       break; 
      } 
     } 
    } while (countr == 1); 
} 

int main() { 
    int userTp = 0; 
    int compTp = 0; 
    int totalTp = 23; 
    int countr = 0; 

    do { 
     if (countr == 0) { 
      cout << "please enter a vale of toothpics between 1 and 3" << endl; 
      cin >> userTp; 
      totalTp += totalTp - userTp; 
      countr++; 
     } 
     else if (countr == 1) { 
      compAlgorithm; 
     } 
    } while (totalTp >= 2); 

    if (totalTp == 1 && countr == 1) { 
     cout << "you win" << endl; 
    } 
    else if (totalTp > 0 && totalTp < 2 && countr == 0) { 
     cout << "please enter a vale of toothpics between 1 and 2" << endl; 
     cin >> userTp; 
     totalTp = totalTp - userTp; 
     switch (totalTp) { 
     case 1: 
      cout << "you win" << endl; 
      break; 
     case 2: 
      cout << "you loose" << endl; 
      break; 
     } 
    } 
    system("pause"); 
    return 0; 
} 

在此先感謝。

+3

聽起來好像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

+1

拼寫:將「你鬆」改爲「你輸了」。 – Frecklefoot

回答

3

這是錯誤的:

else if (countr == 1) { 
    compAlgorithm; 
} 

你必須將參數傳遞給這個函數調用,如果這是你的意圖。目前這條線compAlgorithm;什麼都不做,可能會導致無限循環。

0

我想這可能是因爲如果你沒有指定任何東西,C++通過函數傳遞參數作爲一個值。在函數compAlgorithm中,您必須在totalTpcountr中使用參考,因爲您期望它們超出範圍。我離開你這個link看到更多關於這個。