954,160 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Random no. function dispays the same number

hi

My random number function is meant to loop 6 times & output 6 different numbers. But instead it outputs 6 of the same numbers. How do I fix it? :)

Any advice would be really helpful.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string>


using namespace std;

int random(int max)
{
	srand(time(NULL));

	return ((rand()%max)+1);
}

int main() 
{

for (int i=0; i<6; i++) {
		used_nos[i] = random(40);
		cout << used_nos[i] << endl;
	}

return 0;
}
gretty
Junior Poster
158 posts since Apr 2009
Reputation Points: 10
Solved Threads: 7
 

I'd imagine if you were to wait in the for loop for about a second per iteration it'd be different.

The problem is that you're reseeding the rand function so quickly it's being reseeded off the same value. You only need to seed it once, so do it at the start of main.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string>


using namespace std;

int random(int max)
{

	return ((rand()%max)+1);
}

int main() 
{

	srand(time(NULL));
for (int i=0; i<6; i++) {
		used_nos[i] = random(40);
		cout << used_nos[i] << endl;
	}

return 0;
}


For further clarification... srand takes time(null) in your code, which updates every second, I believe. So if srand was in the function and if the loop executed for over a second you'd get different numbers out every different second.

twomers
Posting Virtuoso
1,877 posts since May 2007
Reputation Points: 453
Solved Threads: 57
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You