我在这个答案中找到了一个代码How to generate a random integer number from within a range一个完美的代码,但是这是整数。有没有人知道如何更改此代码,以便统一返回0到1之间的数字?
#include <stdlib.h> // For random(), RAND_MAX
// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = random();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
答案 0 :(得分:1)
你真的不需要那些复杂的代码。想象一下,你在main函数中正确地初始化了伪随机数生成器,例如rand就是这样:
srand(time(NULL));
以下代码应该足够了:
double random(){
return (double)rand()/RAND_MAX;
}
这个想法只是在0和RAND_MAX之间选择一个随机数,然后将其除以RAND_MAX。当RAND_MAX / RAND_MAX等于1时,您将返回0到1之间的随机值。
答案 1 :(得分:0)
C路:
#include <stdlib.h>
int main(int argc, char** argv)
{
printf("Random value: %f\n", (float(rand()) / float(RAND_MAX));
return 0;
}
C ++ 11方式:
#include <random>
int main(int argc, char** argv)
{
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(0.0, 1.0);
printf("Random value: %f\n", distribution(generator));
return 0;
}