Precision to drand48

Precision to drand48

本文关键字:drand48 to Precision      更新时间:2023-10-16

如何在C++中为drand48()添加精度?我在一个类似的功能中使用它

double x = drand48()%1000+1;

以生成低于1000的数字。但后来我得到了这个错误:

error: invalid operands of types ‘double’ and ‘int’ to binary ‘operator%’

当我使用时不会发生这种情况

double x = rand()%1000+1;

为什么rand()和drand48()有什么区别?

drand48返回区间[0.0, 1.0)的一个数字。你在找1到1000之间的数字吗?在这种情况下,您需要乘以999并加1。

事实上,你在期待什么?

drand48()返回double,而rand()返回int

此外,drand48()返回一个分布在[0.0, 1.0)之间的值,因此您的公式需要更改:

double x = drand48() * 1000.0 + 1; // floating-point values from [1, 1001)

double x = (int)(drand48() * 1000.0) + 1; // integer values from [1, 1000]

您可以如上所述缩放drand48()的结果,也可以将lrand48()与现有公式一起使用。

drand48返回一个介于0.0到1.0之间的双精度。你想把它乘以你想要生成的范围。double x = drand48() * 1000.0