当我使用 rand()
和 srand()
在 [0,1] 中生成随机数时,它给了我这样的数字:0.70324、0.70328、0.70321。 ..
它们仅在最后一位或两位数字上有所不同,而我打算获得随机 float ,例如 0.1,0.7,0.3....
我怎样才能得到这样的随机 float 而不是在最后一位数字上产生差异?
这是我的代码:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
int i;
float randomNum;
for ( i=0; i<10; i++){
srand((unsigned int)time(NULL));
randomNum = ((float)rand())/RAND_MAX;
printf("%f\n",randomNum);
}
return 0;
}
最佳答案
您应该只在程序开始时调用一次 srand()
。在每次调用 rand()
之前调用它只会使结果更可预测,因为每次调用它时使用的数字可能与前一个非常相似。
关于c - 在c中生成范围为[0,1]的随机 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36752991/