C++ Simple Dice roll - 如何返回多个不同的随机数 [英] C++ Simple Dice roll - how to return multiple different random numbers
问题描述
我对 C++ 很陌生,正在尝试使用 Die class/main 制作一个简单的骰子.
I am pretty new to C++ and am trying to make a simple die roll with a Die class/main.
我可以在 1-dieSize 范围内获得一个随机数,但是,每次我掷骰子"时,它只会给我相同的随机数.例如,当我掷骰子三次时,它会掷出 111 或 222 等,而不是 3 个不同的随机掷骰子.任何解释此问题的帮助将不胜感激!
I can get a random number within my range 1-dieSize, however, each time I "roll the dice" it just gives me the same random number. For example, when I roll this dice three times, it will cout 111 or 222 etc instead of 3 different random rolls. Any help explaining this issue would be much appreciated!
我的模头只是一个基本的头.我假设的问题是随机函数.
My die header is just a basic header. My issue I'm assuming is with the random function.
主要:
int main()
{
// Call menu to start the program
Die myDie(4);
cout << myDie.rollDie();
cout << myDie.rollDie(); // roll dice again
cout << myDie.rollDie(); // roll again
return 0;
}
die.cpp:
Die::Die(int N)
{
//set dieSize to the value of int N
this->dieSize = N;
}
int Die::rollDie()
{
// Declaration of variables
int roll;
int min = 1; // the min number a die can roll is 1
int max = this->dieSize; // the max value is the die size
unsigned seed;
seed = time(0);
srand(seed);
roll = rand() % (max - min + 1) + min;
return roll;
}
在 die.cpp 中,我包含了 cstdlib 和 ctime.
In die.cpp I have the cstdlib and ctime included.
推荐答案
正如 melpomene 在评论中所建议的,您应该在程序的某个时刻只初始化一次随机的 seed
.
As melpomene suggested in the comment you should initialize the seed
of the random only once at some point of the program.
rand()
函数并不是真正的随机数创建器,而是对先前生成的值进行位操作的序列,它从种子生成的第一个值开始(调用 <代码>srand(种子)).
The rand()
function is not really a random number creator, rather a sequence of bit manipulation on the previously generated value, which starts with the first value that is generated by the seed (calling srand(seed)
).
#include <iostream>
#include <cstdlib>
int rollDie()
{
int roll;
int min = 1; // the min number a die can roll is 1
int max = 6;// this->dieSize; // the max value is the die size
roll = rand() % (max - min + 1) + min;
return roll;
}
int main()
{
srand(time(0));
for(int i=0;i<10;i++)
{
std::cout << rollDie() << std::endl;
}
}
很有可能你已经在使用 C++11,所以你应该阅读和练习随机库:http://en.cppreference.com/w/cpp/numeric/random
There is a good chance that you are already using C++11, so you should read and practice with the random library: http://en.cppreference.com/w/cpp/numeric/random
这篇关于C++ Simple Dice roll - 如何返回多个不同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!