2017-04-05 104 views
-3

我是新來的StackOverflow,也有些新的程序,所以請不要介意我的代碼格式不佳。我的代碼有兩個問題。我的do ...邏輯和繼續邏輯有什麼問題?

  1. 我繼續聲明,如果玩家輸入'y'或'Y',我用它來繼續循環不起作用。它終止正確得到猜測後程序,這使我:

2.My繼續計數器變爲0過去不停止,我看不出我的錯誤在程序的邏輯。

我看不到我的邏輯問題。

#include "stdafx.h" 
    #include <iostream> 
    #include <iomanip> 
    #include <ctime> 
    #include <random> 

    using namespace std; 

    int getNumber(); //random number prototype 
    double getScore(); //gets score 
    int chances = 7; //chances to guess with 
    int main() 
    { 
    int guess = 0, 
     random; 
    char retry = 'y'; //initialize retry to 'y' 
    cout << "This is a random number guessing game. " << "You will be guessing between 1-100." 
    << "You have 7 chances. Good luck! \n \n" << endl; 


    random = getNumber(); //give the function a variable 

    do 
    { 

    cout << random << "\n" << "\n"; 
    chances--; 

    cout << "Enter your guess: "; 
    cin >> guess; 

     if (guess == random) 
     { 
      cout << "You have won the game! " << "Your score was: " << getScore(); 

      cout << "Would you like to retry? (Y or N): "; 
      cin >> retry; 

      if (retry == 'y' || retry == 'Y') 
      { 
       chances = 7; 
       guess = 0; 
       getNumber(); 
       continue; //player can retry the game 
      } 
      else if (chances == 0) 
      { 
       cout << "You have no chances left. Retry? (Y or N): "; 
        cin >> retry; 
       if (retry == 'y' || retry == 'Y') 
       { 
        chances = 7; 
        guess = 0; 
        getNumber(); 
        continue; 
       } 
      } 

       return 0; 
     } 
     else if (guess != random) 
      cout << "You got it wrong. \n" << "You have: " << chances << " chances left" << endl << endl; 
     else 
      cout << "Incorrect Input. Please type a number." << endl << endl; 
    } while (guess != random); 


return 0; 
} 

int getNumber() 
    { 
    unsigned seed = time(0); //seed the random number 
    srand(seed); 

    int randNum = rand() % 10 + 1; //random number in the range of 1-10 
    return randNum; 
    } 
+1

我不介意你可憐的格式。新的並不妨礙你花費一些時間和精力來很好地設計你的代碼。舉例來說,您可以查看任何現有的成功問題。 Stack Overflow有一個很棒的實時文章預覽,所以你可以花費盡可能多的時間來創建好文章。 –

+1

'如果(重試==「Y」 ||「Y」)'這並不做什麼,你認爲它 – JackVanier

回答

1

你會想看看this

continue語句跳躍至年底,並檢查條件,guess != random,其計算結果爲false,並退出do while。你需要做的是將猜測重置爲一個值,例如0,以使條件確實計算爲true

+0

謝謝你解釋。我看不到發生了什麼事。我不知道我必須重新設定猜測。我之所以必須重置它,是因爲當它繼續時,它會檢查猜測是否等於隨機,並且由於玩家正確,它會自動爲假,退出遊戲? –

2
if (retry == 'y' || 'Y') 

這是不正確的邏輯,這就是爲什麼你的代碼不工作,你希望它的方式。你希望它是:

if (retry == 'y' || retry == 'Y') 

修復在其他if-else語句此邏輯錯誤也是如此。

+0

謝謝你,我甚至沒有意識到這一點。我編輯了我的代碼,但是當播放器輸入時仍不會重啓循環。我將繼續尋找問題。再次感謝你! –

+0

@CoryAhapow如果我的答案有效,請選擇我答案旁邊的複選標記。當你這樣做時它會變成綠色。謝謝! –