C++ Simple Dice roll - how to return multiple diff

2019-09-21 16:06发布

This question already has an answer here:

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条回答
Juvenile、少年°
2楼-- · 2019-09-21 16:54

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

查看更多
登录 后发表回答