精确到drand48

fre*_*ter 4 c++

如何在C++中为drand48()添加精度?我在一个函数中使用它:

double x = drand48()%1000+1;
Run Code Online (Sandbox Code Playgroud)

生成1000以下的数字.但后来我得到这个错误:

error: invalid operands of types ‘double’ and ‘int’ to binary ‘operator%’
Run Code Online (Sandbox Code Playgroud)

当我使用时,这不会发生:

double x = rand()%1000+1;
Run Code Online (Sandbox Code Playgroud)

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

Rog*_*mbe 8

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

实际上,你在期待什么?


NPE*_*NPE 5

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

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

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

要么

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

您可以按比例缩放结果drand48(),也可以lrand48()与现有公式一起使用。