Generating random number on set interval in C

2019-05-05 00:56发布

问题:

I do know python and it is so simple to create a random number on a set interval but then in C it is a little more complicated it seems. So here is what I have by looking at other questions on stack overflow.

int diceroll_1;
diceroll_1=(rand()%3)+1;
printf("%d\n",diceroll_1);

The problem is that it gives me 3 every time. I want it to be different every time the program is compiled and run. I want it to be from 1 to 3 random. My understanding is that this might save it and that is why it is generating 3 every time and not what I want. How do I generate a random number every time and not the same number?

回答1:

Did you seed srand? If not, try like this:

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

int main(void)
{
    srand(time(NULL)); // only once

    // roll the dice
    int diceroll_1;
    diceroll_1=(rand()%3)+1;
    printf("%d\n",diceroll_1);

   return 0;
}

Output:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
3
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
1

PS:

rand() produces pseudorandom numbers, as our prof. in IP insisted! It needs to be seeded, otherwise it will give the same numbers again and again, since from the ref we have that:

If no seed value is provided, the rand() function is automatically seeded with a value of 1.



回答2:

The rand function works by taking the previous random number generated, performing some permutation on it, then returning that. If it's the first time calling rand, it will take the value of the seed for the random number generation sequence and permute that.

Remember that computers are fundamentally deterministic machines and "randomness" doesn't really exist at the hardware/CPU instruction level barring newfangled devices like TRNGs.

High level languages like Python may hide this from you and take care of seeding the random number generation to the system time automatically, behind the scenes, but C will not. You need to call srand with a seed value before calling rand.

Now, calling srand with arguments like srand(3); and srand(100); will generate different random numbers from each other, they will be the same sequence each time. If you want a truly unique value for the seed, try using the current system time:

srand((unsigned)time(NULL));



标签: c random