在if语句中未识别滚动骰子号

Rolling dice number not being recognized in if statement

本文关键字:滚动 识别 if 语句      更新时间:2023-10-16

我得到了一个小程序没有意识到,如果用户滚动6,他们会赢得折扣。当骰子最终掷出6时,它仍然将其视为失败,并告诉用户支付全部金额。我该如何解决这个问题?

我的班级:

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

我的if语句:

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

基本上,请查看@paulevans的答案。我想将重点放在您的rolled功能上:

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

请注意您正在使用rand函数获取随机值。的确,您可以通过使用此功能获得随机值,但我建议使用C 11方法 - 具有更好的分布(别忘了#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;
}

有关更多详细信息,请参见:https://stackoverflow.com/a/13445752/8038186

您不是存储卷,而是想要这个:

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