我用C写了一个简单的代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int val = rand();
printf("val = %d",val);
}
并且我写了一个简单的bash(编译和执行过去的C程序)
gcc test.c
gcc -o test test.c
./test
问题是每当我执行 bash 时,它总是返回相同的值:val = 1804289383
我怎样才能让它按预期返回随机值??
最佳答案
给定相同的起点,重复调用 rand
将始终生成可预测的值流。更改此设置的方法是为生成器播种一个变化的值。您可以通过调用 srand 来完成此操作.
假设您不需要每秒运行一次以上的程序,当前时间将是选择种子的一种廉价/简单的方法。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int val = rand();
printf("val = %d\n",val);
}
我对您的程序做了另一个小改动。输出有时是行缓冲的,所以我在 printf
字符串的末尾添加了换行符 \n
。
关于c - C 中的 rand() 函数返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18392255/