简体   繁体   中英

Newbie random number generator in C question?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, const char *argv[]) {
    srand(clock());
    int num = rand() % 6 + 1;

    printf("%i", num);
    return 0;
}

I get this warning in "srand(clock());" line.

Warning: Implicit conversion loses integer precision: 'clock_t' (aka 'unsigned long') to 'unsigned int'

How do I fix it? Thanks!

Don't use srand(clock()) use srand((unsigned)time(NULL)) instead .

Better seeds:

  • Use time(NULL) to get the time of day and cast the result to seed srand().

  • time(NULL) returns the number of seconds elapsed since midnight January 1st, 1970.

  • Use rdtsc() to get the CPU timestamp and cast the result to seed srand(). rdtsc() is unlikely to return duplicate values as it returns the number of instructions
    executed by the processor since startup.

You should also read this article at US-CERT Secure Coding on how properly seed .

Although it is not an answer to your exact question, it is very relevant to your program –

I read in Stanford CS106 Course Reader available in PDF that int num = rand() % 6 + 1; is not the right way to get a random number between 1 and 6.

I quote the Course Reader:

The problem here is that rand() guarantees only that the value it produces is uniformly distributed over the range from 0 to RAND_MAX. There is, however, no guarantee that the remainders on division by six will be at all random.

They also explain how to do this correctly, which involves four different steps (Normalisation - Scaling - Translation - Conversion).

I thought since you are trying to get your head round the random numbers generator, you might want to know this.

Happy coding!

You can also use:

srand(time(NULL));

which will eliminate possible (highly highly highly unlikely) duplicates.

你可以明确地施展它:

srand((unsigned int)clock());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM