Why is this not a random number?

For the following code snippet:

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

int main()
{
    int x;
    x = rand()%100;
    printf("The Random Number is: %i", x);

return 0;
}

It seems like a random number is printed like 83. Why is this?

+5
source share
6 answers

Most random number generators are repeatable. You need to seed the generator before using it, which you usually use using system time.

#include <time.h>
srand(time(NULL));
+6
source

XKCD required link:

enter image description here

As people said, you need to correctly plant a pseudo-random number generator.

, . "" , (, ).

XKCD . .

enter image description here

+6

, rand, .

, srand , , srand(time(NULL)).

+4

83 - , ?

, , , rand , .

+3

, <time.h> srand(time(0)); ( )

+1

, , , peter. C . (max min):

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

#define MIN 1
#define MAX 5
#define QUANTITY 5

int main()
{
     int i;
     //stores the time in seconds
     time_t seconds;
     //getting the system time
     time(&seconds);
     //initializing the random generator with system time
     //as the seed value
     srand((long)seconds);

     for(i = 0; i < QUANTITY; i++)
     {
           printf("%f\t",((float)rand())/RAND_MAX*(MAX-MIN)+MIN);
     }
     printf("\n");

     return 0;
}
0

All Articles