I got a small program where in the end, the program asks the user if he/she wants to roll dice to win an extra 15% off their initial check, but my if statement is not recognizing that if the user rolls a 6, they win the discount. When the dice eventually rolls a 6, it still reads as a fail and tells the user to pay the full amount. How can I work around this?
My class:
class roll
{
private:
int high;
public:
roll(int high = 6)
{
this->high = high;
}
~roll()
{
}
int rolled(int amt = 1)
{
int done = 0;
for (size_t x = 0; x < amt; x++)
{
done += rand() % high + 1;
}
return done;
}
};
My if statement:
cout << "Would you like to play a dice game for a discount? Y/N: " << endl;
cin >> res;
if (res == 'Y' || res == 'y')
{
srand(time(static_cast<unsigned>(0)));
roll one;
cout << one.rolled() << endl;
if (one.rolled() == 6)
{
cout << "Congratulations! You won 15% off your meal!!!" << endl;
prize = grandtot - (grandtot * .15);
cout << "Your final total will be $" << prize << endl;
}
else
{
cout << "Sorry, you did not win, pay the original amount!" << endl;
}
}
else
{
cout << "Thank you, pay the original amount and have a nice day!" << endl;
}
rolled
will (usually) return a different number if you call it a second time. (I think everyone falls into this trap more or less regularly.)prize = grandtot - (grandtot * .15);
is equivalent toprize = grandtot * .85;
srand(time(static_cast<unsigned>(0)));
You should call this 1 time at the beginning of main and avoid putting it in a loop. Remember that the resolution of the clock is 1 second. And also if the seed is the same you get the same random sequence. Meaning if this loop executes fast enough you will get the same roll multiple times in a row.rand()
. There's whole c++11 new library<random>
that does RNG correctly.