kingIchabodCrane
kingIchabodCrane

Reputation: 23

Rolling dice number not being recognized in if statement

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;
            }

Upvotes: 2

Views: 125

Answers (2)

Coral Kashri
Coral Kashri

Reputation: 3506

Basically, look at @PaulEvans answer for your question. I want to put some focus on your rolled function:

int rolled(int amt = 1)
{
    int done = 0;

    for (size_t x = 0; x < amt; x++)
    {
        done += rand() % high + 1; // <= This line
    }
    return done;
}

Pay attention that you are using rand function to get random values. It's true that you can get random values by using this function, but I would recommend to use C++11 way - with better distribution (don't forget #include ):

int rolled(int amt = 1)
{
    int done = 0;
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    for (size_t x = 0; x < amt; x++)
    {
        done += dist6(rng); // <= This line
    }
    return done;
}

For more details see: https://stackoverflow.com/a/13445752/8038186

Upvotes: 6

Paul Evans
Paul Evans

Reputation: 27577

You're not storing your roll, you want this instead:

const int current_roll = one.rolled();
cout << current_roll << endl;
if (current_roll == 6)
...

Upvotes: 5

Related Questions