When I trace this program line by line, I get different outputs(which is what I want). However, when I compile and run, output values are all the same. Why is this the case?
I initialised the seed outside the function roll_dice (I put it in the main) and the output is fine.
Code:
/*
* Craps game
*/
#include <stdio.h>
#include <stdlib.h> //for srand and rand
#include <time.h>
int roll_dice(void);
int play_game(void); //returns true or false
int main()
{
int x;
//srand((unsigned) time(NULL)); //produces correct result
for (x = 0; x < 100; x++)
play_game();
getchar();
return 0;
}
int roll_dice(void)
{
int first_roll, second_roll, sum;
srand((unsigned) time(NULL)); //initialised in main-> output rite
first_roll = rand() % 7;
second_roll = rand() % 7;
sum = first_roll + second_roll;
return sum;
}
int play_game(void) //return bool
{
printf("%d\n", roll_dice());
return 0;
}
Is this right?
1. For x = 0, play_game function is called
2. in play_game function, roll_dice() function is called
3. in roll_dice function, seed is initialised and the sum is returned to play_game function
4. sum is printed
In step 3, the srand function should be initialised with a new seed. Seems like the same seed keeps getting initialised
5. repeat step 1, x++
Solved: srand initialises new seed every second. At the moment, srand is called 100 times within 1 second, hence the same seed is used for the rand() function.
used this for anyone who sees this in the future
c - Problems when calling srand(time(NULL)) inside rollDice function - Stack Overflow
c - srand() -- why call only once? - Stack Overflow