-1

I don't understand why i keep getting the same random number for player and computer. I am rolling a die twice, once for player and then for the computer and I am doing it via a function called roll_a_dice

Plz ignore the other variables they're irrelevant to my question.

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




int roll_a_dice (void);

int main(int argc, const char * argv[]) {

int round=1, playerScore, playerTotal, computerScore, computerTotal;
int player, computer;


do{
    printf("Welcome to the Yacht game.\nLets see who is lucky!\n");

    player=roll_a_dice ();
    computer=roll_a_dice ();
    printf("Player: %d – Machine: %d\n",player, computer);

}while (player!=computer||computer!=player);



while(round!=12){



round++;

}

return 0;
}
int roll_a_dice (void){


srand(time(NULL));

return 1 + rand() % 6;


}
RedDoumham
  • 51
  • 7

1 Answers1

2

rand() generally uses a pseudorandom number generator... it's not truly random, it just gives a seemingly random sequence of numbers (over a series of calls). srand() "seeds" it, basically determining where the sequence starts. So if you use the same seed, you get the same sequence.

Since you call roll_a_dice() twice close together, time(NULL) will usually give the same result for both calls (since they're likely within the same second), so you reseed with the same value each time and get the same number (the first in that sequence).

You only need to seed once, before the first time you call rand(). Calling srand() again needlessly restarts the sequence of numbers, according to the seed value you pass it.

Dmitri
  • 9,175
  • 2
  • 27
  • 34