0

I've recently written a little program to test the C rand function found in <math.h>.

I've compiled it twice and run it multiple times. On every run, the same output was printed out:

2
2
6
3
5
3

Can someone point out the problem?

Here is the code:

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

int pick(int start, int end){
    int num  = ( rand()%end ) + start;
    return num;
}

int main(){

    int i;
    for(i=0; i<6; i++){
        printf("%d\n", pick(1, 6));
    }
    return 0;
}
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Serket
  • 3,785
  • 3
  • 14
  • 45
  • You should seed it with the srand() function. – Toggy Smith Apr 09 '20 at 17:03
  • `rand()` doesn't generate a truly random sequence - it generates a pseudo-random sequence using a deterministic algorithm, so for the same starting value (seed) it will always generate the same sequence. Unless you specify a seed with `srand()`, it will always assume a seed of 1. – John Bode Apr 09 '20 at 17:35

1 Answers1

0

From the man page of rand():

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

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

Community
  • 1
  • 1
Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62