到目前为止这是我的文件:
#include <stdio.h>
int main(void) {
int y;
y = generateRandomNumber();
printf("\nThe number is: %d\n", y);
return 0;
}
int generateRandomNumber(void) {
int x;
x = rand();
return x;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是rand()总是返回41.我在win上使用gcc ...不知道该怎么做.
编辑:使用时间生成随机数将无法正常工作.它为我提供了一个数字(12000),每次我调用它只是稍微高一点(大约每秒+3).这不是我需要的随机性.我该怎么办?
你需要提供种子.
来自网络 -
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, stime;
long ltime;
/* get the current calendar time */
ltime = time(NULL);
stime = (unsigned) ltime/2;
srand(stime);
for(i=0; i<10; i++) printf("%d ", rand());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
标准技巧是:
srand(time(0)); // Initialize random number generator.
Run Code Online (Sandbox Code Playgroud)
注意:该功能srand不是rand.
在您的main功能中执行此操作一次.之后,只打电话rand来获取号码.
根据实现,它还可以帮助获取和丢弃一些结果rand,以允许序列偏离种子值.