如何生成0和max之间的随机二重(在C中)



以下是我生成随机双精度的方法:

int main()
{
srand(time(NULL));
double max = 10.0;
double x = (double)rand()/(double)(RAND_MAX/max);
printf("The random number is %f n", x);
}

尽管它生成的数字本质上是随机的,但它仍然不够随机。

我第一次跑步时得了7.303385然后我得了7.320475。然后我得了7.332377。然后我得了7.345195。

你明白了。看起来我的代码只生成7.3到7.4之间的随机数。

我在这里做错了什么?

编辑:

我刚刚注意到的另一件奇怪的事情:

我稍微修改了一下代码:

int main()
{
srand(time(NULL));
double max = 10.0;
double x = (double)rand()/(double)(RAND_MAX/max);
double y = (double)rand()/(double)(RAND_MAX/max);
printf("The random number is %f n", x);
printf("The random number is %f n", y);
}

当我运行这个程序时,x总是给我一个介于7.3和7.4之间的值,所以这里没有变化。然而,y总是生成0到10之间的值,这正是我想要的。那么,为什么x的行为不同呢?

我不知道你的代码是什么样子的,但这很好:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));    // call srand once only
for (int i = 0; i < 50; i++)
{
//  srand(time(NULL));  // don't put srand here
double max = 10.0;
double x = (double)rand() / (double)(RAND_MAX / max);
double y = (double)rand() / (double)(RAND_MAX / max);
printf("The random number is %f n", x);
printf("The random number is %f n", y);
}
}

不同的问题:

您可能需要RAND_MAX/max;而不是(double)(RAND_MAX/max);,否则如果max很大,您可能会遇到问题。

最新更新