gpt4 book ai didi

c++ - if 语句中无法识别掷骰子数

转载 作者:太空狗 更新时间:2023-10-29 23:34:54 25 4
gpt4 key购买 nike

我有一个小程序,最后,该程序询问用户他/她是否想掷骰子以赢取初始支票额外 15% 的折扣,但我的 if 语句无法识别用户是否掷骰子6、他们赢得折扣。当骰子最终掷出 6 时,它仍视为失败并告诉用户全额支付。我该如何解决这个问题?

我的类(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;
}

};

我的 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

关于c++ - if 语句中无法识别掷骰子数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56186172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com