gpt4 book ai didi

c++ - 如何模拟不同面数的骰子卷?

转载 作者:行者123 更新时间:2023-12-02 10:21:07 25 4
gpt4 key购买 nike

以下代码采用用户提供的骰子边数,然后调用一个函数以返回骰子掷骰的随机结果。但是,我不知道如何生成介于1和提供的数字之间的随机数。

#include <iostream>
using namespace std;
int main() {
int numberOfSides = 0;

do
{
cout << "How many sides do you want the die to have? ";
cin >> numberOfSides;
if (numberOfSides <= 0)
{
cout << "Error: Please enter a positive integer!" << endl << endl;
}
} while (numberOfSides <= 0);

int result = rollDie(numberOfSides);
cout << "You rolled a " << result << endl;
}

int rollDie(int numberOfSides)
{
// Complete this function
}

最佳答案

作为示例,在C++引用中描述了随机数生成。

请查看here

您也可以在此处找到说明。我用引用代码完成了您的功能。

请参阅:

#include <iostream>
#include <random>

int rollDie(int numberOfSides)
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, numberOfSides);
return dis(gen);
}


int main() {
int numberOfSides = 0;

do
{
std::cout << "How many sides do you want the die to have? ";
std::cin >> numberOfSides;
if (numberOfSides <= 0)
{
std::cout << "Error: Please enter a positive integer!\n\n";
}
} while (numberOfSides <= 0);

int result = rollDie(numberOfSides);
std::cout << "You rolled a " << result << "\n";
}

关于c++ - 如何模拟不同面数的骰子卷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60125153/

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