if语句

时间:2019-05-17 12:12:22

标签: c++

我有一个小程序,最后,该程序询问用户是否要掷骰子以赢得其初始支票额外15%的折扣,但是我的if语句无法识别用户是否掷骰子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;
            }

2 个答案:

答案 0 :(得分:6)

基本上,请查看@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

答案 1 :(得分:5)

您不是要存储纸卷,而是要保存纸卷:

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