Reputation: 31
I am somewhat new to C, but I have had this same problem with a variety of different languages. When using srand(time(NULL)) to generate random numbers, the values come out just fine the first time but any time after that it just keeps the same values. I tried resetting all of the variables to new values above to no effect.
while(Ui <= (uInput - 1))
{
printf("Input answer %d: ", (Ui + 1));
scanf("%d", &answers[Ui]);
Ui++;
srand(time(NULL));
a = (rand() % 25 + 1) - (rand() % 25 + 1);
b = (rand() % 25 + 1) - (rand() % 25 + 1);
c = (rand() % 25 + 1) - (rand() % 25 + 1);
d = (rand() % 25 + 1) - (rand() % 25 + 1);
e = (rand() % 25 + 1) - (rand() % 25 + 1);
f = (rand() % 25 + 1) - (rand() % 25 + 1);
g = (rand() % 25 + 1) - (rand() % 25 + 1);
h = (rand() % 25 + 1) - (rand() % 25 + 1);
i = (rand() % 25 + 1) - (rand() % 25 + 1);
j = (rand() % 25 + 1) - (rand() % 25 + 1);
}
The idea is for this to print off multiple 10-variable equations, variables a-j representing the coefficient of each variable in the equation. The problem is that no matter what I do, it generates and prints the same equation every time, it wont reassign new random values to the variables.
As a side note, I know that my code doesn't look like it accomplishes anything right now, but this is just a snippet that I copied, pasted, and modified so you could see my method for assigning random values.
I greatly appreciate any help, feedback, or support.
Upvotes: 2
Views: 129
Reputation: 24168
Move the srand(time(NULL));
outside the while
loop.
time(NULL)
returns the time_t
struct, which is being converted into the unsigned int
(prototype: void srand( unsigned seed );
), storing total number of seconds since the Epoch: 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.
And the loop executes as fast, so each srand(time(NULL))
being evaluated in the same second.
Upvotes: 6