srand(time(NULL)) in C++

srand(time(NULL)) in C++

本文关键字:in C++ NULL time srand      更新时间:2023-10-16

如果我用srand注释掉这一行,程序将工作,但没有种子,因此每次的值都相同。赋值要求我使用randsrandtime使骰子函数完全随机。

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int rollDice();
// function declaration that simulates the rolling of dice
int main() {
    int roll1 = rollDice();
    int roll2 = rollDice();
    // define, initialize, and combine dice roll total
    int total;
    total = 0;
    total = roll1 + roll2;
    * this is where a bunch of stuff is output to the screen from the dice rolls, using total as well as some other stuff that is being calculated, i left it out for simplicity*
}
// function to simulate a random dice roll
int rollDice() {
    int r;
    srand (time(NULL));
    r = (rand() % 6) + 1;
    return r;
}

srand放在主键上,然后调用它一次。您必须使用一次种子才能从随机序列中获得所有结果。

在这里,每次掷骰子时都会重新启动序列。

有关srand(),请参阅文档