Random number generation on a given interval in C

I know this topic has been addressed before, but I'm still a little confused. I am new to C, so please come with me. I really know python, and it is so simple to create a random number on a given interval, but then in C it is a little more complicated. So, here is what I have when considering other stack overflow issues.

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

The problem is that she gives me 3 every time. I want it to be different every time the program has been compiled and launched. I want it to be 1 to 3 random. I understand that this can save him, and that is why he generates 3 every time, and not what I want. How can I generate a random number every time, and not the same number?

+4
source share
2 answers

Have you settled 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;
}

Conclusion:

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

PS:

rand()creates pseudo-random numbers, as our prof. insisted in IP! It must be sown, otherwise it will give the same numbers again and again, since from ref we have the following:

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

+3
source

The function randworks by taking the previous random number generated, doing some permutation on it, and then returns it. If he calls for the first time rand, he will take the value of the seed for the random number generation sequence and rearrange it.

, , "" / , , TRNGs.

, Python, , , , C . srand rand.

srand , srand(3); srand(100);, , . - , :

srand((unsigned)time(NULL));

0

Source: https://habr.com/ru/post/1661618/


All Articles