我知道这是一个简单的问题,但我似乎无法弄清楚我做错了什么。我应该写一个类似彩票的节目。一个数组包含5个随机数,另一个数组包含用户选择的5个数字。我使用冒泡排序来组织数字,然后尝试比较两个数组。当我运行该程序时,它总是说用户是胜利者,即使他们甚至没有得到正确的单个数字。我已尝试过循环,而循环,if / else,我不知道我哪里出错了。如果你能告诉我我哪里出错了,或者至少引导我走向正确的方向?
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 :(得分:5)
if (winner == true) // Use `==` equality operator
{
cout << "Winner!" << endl;
}
答案 1 :(得分:2)
在你的代码中最后一个条件:
if (winner = true)
将winner
分配给true
,您不是这样做比较:
if(winner==true)