C++ 中的 srand(time(NULL))
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18728807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:10:28 来源:igfitidea点击:
srand(time(NULL)) in C++
提问by user2766542
If I comment out the line with srand
, the program will work, but there is no seed so the values will be the same each time. The assignment requires that I use rand
, srand
, and time
to have the dice function be completely random.
如果我用 注释掉该行srand
,程序将运行,但没有种子,因此每次的值都相同。分配要求我使用rand
, srand
, 并使time
骰子函数完全随机。
#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;
}