I have to write a program that selects a random color from an array. I used the srand (time(0)); statement but it still gives me the same color each time. Does anyone know why? Here is my code.
Do you mean that you get the same colour if you run the program multiple times within the same second? That's because time(0) returns the time in seconds so on the same second you will use the same seed which means you get the same sequence of random numbers from rand(). Programs are usually not run that often so it's usually not a problem.
I used the srand (time(0)); statement but it still gives me the same color each time. Does anyone know why?
In the code you've presented, srand is called a single time so there are not multiple random numbers to compare against. If you invoke the program multiple times, you should receive differing results.
If main looked like this, on the other hand,
1 2 3 4 5 6
int main()
{
Color C ;
for ( unsigned i=0; i<7; ++i )
std::cout << C.getColor() << '\n' ;
}
I would expect it to print out the same number 7 times as srand is called several times in a row (via getColor) with the same value returned from time.