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;
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.