简体   繁体   English

如何比较两个数组C ++

[英]How to compare two arrays c++

I know this is a simple question, but I just can't seem to figure out what I'm doing wrong. 我知道这是一个简单的问题,但是我似乎无法弄清楚自己在做什么错。 I'm supposed to write a program that is like a lottery. 我应该写一个像彩票一样的程序。 One array contains 5 random numbers, and the other contains 5 numbers selected by the user. 一个数组包含5个随机数,另一个数组包含5个由用户选择的数字。 I use bubble sort to organize the numbers, and then try comparing the two arrays. 我使用冒泡排序来组织数字,然后尝试比较两个数组。 When I run the program it always says the user is a winner, even if they didn't even get a single number correct. 当我运行该程序时,它总是说用户是赢家,即使他们甚至没有得到一个正确的数字。 I've tried for loops, while loops, if/else, and I don't know where i'm going wrong. 我已经尝试过循环,而while循环是if / else,但我不知道我要去哪里。 If you could please show me where i'm going wrong, or at least lead me in the right direction? 如果可以,请告诉我我哪里出问题了,或者至少将我引向正确的方向?

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;
}
if (winner == true) // Use `==` equality operator
{
  cout << "Winner!" << endl;

}

In your code the last condition: 在您的代码中,最后一个条件是:

    if (winner = true)

assigns winner to true , you are not comparing it do it this way: winner分配为true ,您没有将其进行这种比较:

    if(winner==true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM