C ++ Simple Dice roll - 如何返回多个不同的随机数[重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

我是C ++的新手,我正在尝试用Die class / main制作一个简单的掷骰子。

我可以在我的范围1-dieSize中得到一个随机数,但是,每次我“掷骰子”时它只给我相同的随机数。例如,当我掷骰子三次时,它会输出111或222等,而不是3个不同的随机卷。任何帮助解释这个问题将不胜感激!

我的标题只是一个基本标题。我假设我的问题是随机函数。

主要:

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。

c++ random dice srand
1个回答
0
投票

正如评论中提到的melpomene你应该在程序的某个时刻初始化随机的seed一次。

rand()函数实际上不是随机数创建者,而是先前生成的值的位操作序列,其以种子生成的第一个值(调用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

© www.soinside.com 2019 - 2024. All rights reserved.