c - 在c中生成范围为[0,1]的随机 float

标签 c random srand

当我使用 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/

相关文章:

c - scanf() 尝试输入带或不带空格的字符串时会关闭程序

python - 在 Python 中使随机模块线程安全

c++ - 物理机器之间的 srand 种子一致性

c - 在 C 中创建一个 StartsWith 函数,得到 "Segmentation fault",有什么问题吗?

c - strncpy导致段错误

c - 如何将 SOCK_DGRAM 转换为 SOCK_RAW?

c - srand()——为什么只调用一次?

我可以使用 main 中 argc 的地址作为随机源吗?

swift - 如何生成用于不记名 token 的加密安全随机数?

algorithm - 是否有可能根据有限的伪随机数序列获得种子的近似值?