我有以下代码:
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
cout << rand()%30<< endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我运行此代码,总是得到11。请解释为什么。我使用最新的代码块和C ++
该rand()函数不会生成真正的随机数;实际上,它会返回一系列从到的值的下一个伪随机值。您可以使用更改该顺序的起点。0RAND_MAXsrand()
一种常见的技术是使用函数srand()使用当前时间进行初始化time(),如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand(time(NULL));
printf("%d", rand());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这将导致程序每次运行时都从序列中的不同点开始生成数字,从而使其难以预测。