Random float number

和自甴很熟 提交于 2019-11-29 03:54:30

You need to call

srand(time(NULL));

before using rand for the first time. time is in <time.h>.

EDIT: As Jonathan Leffler points out, this is easily predicted, so don't try using it for cryprography.

That is because the C random-generator is a pseudo-random generator (and that is, BTW, a very good thing, with many applications). (The ANSI C standard requires such a pseudo-random generator)

Essentially each time your console application is re-started it uses the same [default] seed for the random generator.

by adding a line like

  srand(time(NULL));

you will get a distinct seed each time, and the sequence of number produced with vary accordingly.
Note: you only need to call srand() once, not before each time you call rand().

Edit: (Test/Debug-time hint)
[from a remark by Artelius] For testing purposes, it's best to srand(SOME_CONST), and change the value of the constant between runs. This way if a bug manifests itself due to some combination of random numbers, you'll be able to reproduce it.

drand48 is perfect for your usage, better than (float)rand()/RAND_MAX, because

The drand48() and erand48() functions return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0 , 1.0].

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    int i;

    srand48(time(NULL));

    for (i = 0; i < 10; i++)
        printf("%g\n", drand48());

    return 0;
}

You have to initialize a random seed with

void srand ( unsigned int seed );

You can take for example the system time.

Do you call it more than once? rand() will always return the same pseudo random. You might want to call srand() with some nice seed, like the current time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!