2016-05-15 85 views
1

我試圖跳出一個for循環,在一個嵌套的if語句內。所以基本上我在做MasterMind遊戲,並試圖知道多少用戶實際上是正確的(丟棄位置)。 。所以基本上我想出了將AI的二進制數字存儲在一個數組中,然後將每個用戶二進制數字與它進行比較。只要用戶的二進制數字等於來自AI的一個二進制數字,那麼它應該跳出for環...我想這樣理解,我做的:分手for循環C++

void MasterMind::evaluateCorrection() 
{ 
    // AI : 1 1 1 0 
    //USER: 1 0 1 1 
    //Store AI In Array 
    int AI[3]; 
    int count = 0; 

    std::copy(binaries.begin(), binaries.end(), AI); 
    for(std::vector<char>::iterator itAI= numbers.begin() ; itAI != numbers.end(); itAI++) 
    { 
     for(int i=0; i<=3;i++) 
     { 
      char numberAt = *itAI; 
      int intNumberAt = numberAt - '0'; 
      if(intNumberAt = AI[i]) 
      { 
       cout << intNumberAt << " VS " << AI[i] << endl; 
       actuallyCorrect++; 
       break; 
      } 
     } 
    } 
    cout << "\n ACTUALLY CORRECT " << actuallyCorrect << endl; 
} 

所以,當我得到這個代碼在bash:

BINARY : 
1111 


PLEASE ENTER A 4 DIGIT BINARY! OR PROGRAM WILL EXIT 

     1123 
YOU HAVE 2 POSITIONS CORRECT 
1 VS 1 
1 VS 1 
1 VS 1 
1 VS 1 

ACTUALLY CORRECT 4 

這顯然是不正確的..我進入1123,它只是說4實際上是正確的......實際上只有2,其實是正確的1和1.請幫助!

+1

'AI [3]'是外的範圍,因此必須不能訪問'AI [I]''時I = 3'。 – MikeCAT

+2

'intNumberAt = AI [i]'是一個賦值,而不是比較。你確定這是你想要做的嗎? – MikeCAT

+0

哇@MikeCAT WOWW ...我完成了 – JOHHNYDEP

回答

1
  • AI[3]是超出範圍的,所以你不能訪問AI[i]i=3和數組的大小應該增加。
  • intNumberAt = AI[i]是一項任務。使用==運算符進行平等檢查。

嘗試這種情況:

void MasterMind::evaluateCorrection() 
{ 
    // AI : 1 1 1 0 
    //USER: 1 0 1 1 
    //Store AI In Array 
    int AI[4] = {0}; // initialize for in case what is copied has insufficient number of elements 
    int count = 0; 

    std::copy(binaries.begin(), binaries.end(), AI); 
    for(std::vector<char>::iterator itAI= numbers.begin() ; itAI != numbers.end(); itAI++) 
    { 
     for(int i=0; i<=3;i++) 
     { 
      char numberAt = *itAI; 
      int intNumberAt = numberAt - '0'; 
      if(intNumberAt == AI[i]) 
      { 
       cout << intNumberAt << " VS " << AI[i] << endl; 
       actuallyCorrect++; 
       break; 
      } 
     } 
    } 
    cout << "\n ACTUALLY CORRECT " << actuallyCorrect << endl; 
} 
+0

也許是op想要AI [4]。關於'if(intNumberAt = AI [i])的好的觀察'。我最近讀了1993年困擾Sunsoft的優先級1的一個bug。經過一些密集的調試會話之後,他們將它追蹤到一個讀取'x == 2' 。程序員的手指已經在等號鍵上反彈,意外地按了兩次而不是一次。這裏操作符可能有一個「等號」鍵,不願意承認按鍵。 ;) – sjsam