hey everyone im trying to write a program that generates 5 random numbers from the cpu and have the user input 5 numbers. depending on the user's input if the numbers match up the user wins 100$/number matched with the cpu.
Actually a simple if statement might not do it unless the OP wants to compare the position as well.
i.e.
winningDigits = {1,2,3,4,5}
player = {5,4,3,2,1}
1 digit matched '3'
If you the OP want's to do something kinda like the lottery where order doesn't matter then I'd suggest a sort on both arrays and then compare for equal and less than...
position does matter in my particular case but i just do not know how to format the loop for the program to match both the player and the random winning numbers if that makes sense. thank you.
bool equal = true;
for(int i = 0; i < numbers; ++i)
{
if(winningDigits[i] != players[i])
{
equal = false;
break; //exit the loop could replace this
//if you do equal = winningsDigits[i] == players[i]
//then instead of i < numbers you put i < numbers && equal
}
}
if(equal)
{
std::cout << "The two arrays are the same!" << std::endl;
}
else
{
std::cout << "The arrays are not the same!" << std::endl;
}
But still you'd require a sort first as he said the order doesn't matter, a magnitude sort will place all values in the same position (if they match that is)
Once doing the sort you can then either just check if they all match with your code, just iterating through and checking if each element is equal... OR you can actually check how many of them are equal with the functions I wrote, which is useful for things like lottery where you have larger prizes for matching more numbers.
//for loop for the winning numbers
for (int i=0; i<5; ++i)
{
winningDigits[i] = rand()%10;
}
//print out the winning numbers
for (int i=0; i<5; ++i)
{
cout<<winningDigits[i]<<" ";
}
Why not output after getting the number?
1 2 3 4 5 6 7 8
//I would avoid the magic numbers (5 & 10)
//give them a good name like numberOfDigits
//and maxValue/upperLimit
for(int i = 0; i < 5; ++i)
{
winningDigits[i] = rand() % 10;
cout << winningDigits[i] << ' ';
}
You also have a few things that can be easily done with loops:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//allow the player to enter 5 digits
cout<<"enter 5 digits:";
cin>> player[0];
cin>> player[1];
cin>> player[2];
cin>> player[3];
cin>> player[4];
//disply player input
cout<<" "<< player[0];
cout<<" "<< player[1];
cout<<" "<< player[2];
cout<<" "<< player[3];
cout<<" "<< player[4];
could just as easily been written as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
cout << "Enter 5 digits: ";
for(int i = 0; i < numberOfDigits; ++i) //mentioned earlier to avoid magic numbers like 5
{
cin >> player[i];
}
//or you could even have done:
//cin >> player[0] >> player[1] >> player[2] >> player[3] >> player[4];
cout << "Player digits: ";
for(int i = 0; i < numberOfDigits; ++i)
{
cout << player[i] << ' ';
}