Sean.D - 1 year ago 68
C Question

# Generating random number on set interval in C

I know this topic has been covered before, but I am still a little confused. I am brand new to C, so please bare with me. 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?

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download