Archived

This topic is now archived and is closed to further replies.

srand, rand crt functions

This topic is 4988 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I just found this simple problem, that I don't want to slove in a sloppy way.
#include <string>
#include <stdio>
#include "stdlib.h"
#include "time.h"

int main() {

	int MyRandNumber = 0;

	string CmdInput;
	while(cin >> CmdInput) {
		if(CmdInput == "rand") {
		for(int i=0;i < 5; i++) {
			srand((unsigned)time(NULL));
			MyRandNumber = rand()%5; //Answer will be from 0-4.

			cout << "# = " << MyRandNumber << endl;
		} // end for

		} //end if

	} // end while

return 0;
} // end main

Really basic stuff, I recreated my problem with this. srand uses the time to gen a true random number when you use rand(). So if you type rand and press return, you should see all random numbers from 0-4. However, I get a random number except all the same for each batch. Example, I type "rand" then hit return # = 0 # = 0 # = 0 # = 0 # = 0 I type "rand" then hit return # = 4 # = 4 # = 4 # = 4 # = 4 ... and so on I need each # to be random! I hope I'm not overlooking something simple. Thanks in advance. [edited by - chbfiv on April 22, 2004 2:43:29 PM]

Share this post


Link to post
Share on other sites
don''t call srand in your loop call it only once at the begining of your program

When you call srand with the same number you will get the same series of random numbers returned (because there not truely random they are generated from a very hard to detect pattern)

even though you seed it with the return from time() its returning the same number each time because your loop is executed very quickly, and this is just need neccessary anyways you call srand once and rand will return a different number each time you call it

Share this post


Link to post
Share on other sites