General Question

Mariah's avatar

Can you help me understand why my code is wrong?

Asked by Mariah (25883points) January 26th, 2013

This is homework. Please don’t write any code for me.

I am programming in C and I am supposed to fill an array with random numbers. There should be two separate functions – one that generates a random number, and one that calls the other to fill an array.

My function that generates a random number is working fine. I know because I compiled it and ran it a few times and got different numbers. Yet, when I run the second function, I end up with an array containing all the same number. This number changes when I run it again, but all the numbers are always the same.

The basic outline of my second function is:

int myArray[size];
for(int i=0; i<size; i++){
myArray[i] = generateRandomNumber();
}

I think this might be happening because the random numbers are generated using the computer’s clock, and the program runs through them so fast that the clock doesn’t change and so all the numbers turn out the same. Do you think that might be what’s happening, or is it something on my end? If that’s what’s happening, what the heck should I do about it?

Observing members: 0 Composing members: 0

6 Answers

Mariah's avatar

OK I was right about what was causing it. I added a brief sleep between each random number generation. If someone has a better suggestion, my ears are open.

yankeetooter's avatar

Well…did you test the program after making this change? What were the results? And can I see the rest of your code?

Mariah's avatar

Yes, it worked after I had it sleep!

phaedryx's avatar

A common solution is to seed the first call to generateRandomNumber() with the clock, but also store the value of the call. Subsequent calls seed with the previous (stored) value. Does that make sense?

Response moderated (Spam)
Response moderated (Unhelpful)

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther