问题
I am pretty new to C++ and am trying to make a simple die roll with a Die class/main.
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.
main:
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;
}
In die.cpp I have the cstdlib and ctime included.
回答1:
As melpomene suggested in the comment you should initialize the seed
of the random only once at some point of the program.
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;
}
}
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
来源:https://stackoverflow.com/questions/45133700/c-simple-dice-roll-how-to-return-multiple-different-random-numbers