2014-04-11 83 views
1

我知道這是一個簡單的問題,但我似乎無法弄清楚我做錯了什麼。我應該寫一個像彩票一樣的程序。一個數組包含5個隨機數字,另一個數組包含用戶選擇的5個數字。我使用冒泡排序來組織數字,然後嘗試比較兩個數組。當我運行程序時,它總是說用戶是贏家,即使他們甚至沒有得到正確的數字。我嘗試過循環,while循環,if/else,並且我不知道我錯在哪裏。如果你能告訴我我哪裏出錯了,或者至少讓我走向正確的方向?如何比較兩個數組C++

int main() 
{ 
    // Variables 
    int winningNumbers[5] = {}; 
    int numbersToPlay[5] = {}; 
    bool winner = true; 

    std::random_device rd; // obtain a random number from hardware 
    std::mt19937 eng(rd()); // seed the generator 
    std::uniform_int_distribution<> distr(1, 40); // define the range 

    for (int i = 0; i < 5; i++) 
    { 
     winningNumbers[i] = distr(eng); 
    } // generate random lotto numbers 

    // sort lotto numbers low to high 
    bubbleSort(winningNumbers); 

    // prompt user to select numbers to play 
    cout << "Input 5 numbers [1-40]: "; 
    for (int i = 0; i < 5; i++) 
    { 
     cin >> numbersToPlay[i]; 
    } 

    // sort played numbers 
    bubbleSort(numbersToPlay); 

    // check for winner 
    int index = 0; 
    while (index < 5) 
    { 
     if (numbersToPlay[index] == winningNumbers[index]) 
     { 
      winner = true; 
      index++; 
     } 
     else 
     { 
      winner = false; 
      break; 
     } 
    } 

    if (winner = true) 
     cout << "Winner!" << endl; 
    else 
     cout << "Not a winner..." << endl; 

return 0; 
} 
+0

始終編譯代碼的警告啓用(gcc中的'-Wall')。 –

+0

另外,不需要在while循環中設置winner = true。從初始化開始已經是真的了。當它變得虛假的時候,你打破循環並離開。 –

回答

2

在你的代碼中的最後一個條件:

分配winnertrue,你是不是比較它做這種方式:

if(winner==true) 
5
if (winner == true) // Use `==` equality operator 
{ 
    cout << "Winner!" << endl; 

} 
+0

每當有人在SO上詢問「爲什麼我的if語句不起作用?」答案總是「use'=='not'='」。每一次。 – CoryKramer

+0

@Cyber​​你還想要我寫什麼,顯然OP知道'if'構造中的'='和'=='之間的區別,因爲他/她已經在上面使用它了,如果我指出,他一定知道問題,不是嗎? – P0W

+0

我並不是說你不正確,那正是問題所在。我只是開玩笑地說,這是一個非常常見的初學者問題。 – CoryKramer