Repeating a function

New to C++ and programming in general. In my class my professor is asking us to create a user guided random number generator. Im having an issue with repeating the random number generator "x" amount of times with it generating a different number each time. Any ideas would be greatly appreciated!!

#include <iostream>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main() {

int x; // amount of random numbers
int maxRange; // random number high
int minRange; // random number low
int randomNum;

cout << "What is your random number high?" << endl;
cin >> maxRange;
cout << "What is your random number low?" << endl;
cin >> minRange;
cout << "How many random numbers do you want?" << endl;
cin >> x;

for(int i = 1; i <= x; i++){

srand (time(0));
//generates random number between users input of max and min
randomNum = rand() % maxRange + minRange;


cout << "The random number is: "<<randomNum<<endl;
}
}
Move srand(time(0)); to before and outside of the loop.
srand is only called once to see the RNG.
You don't need to seed your random number generator in each iteration of your for-loop. You can initialize your random number generator once by putting srand(time(0)) outside the for-loop structure.

Also, this is unrelated to your actual bug, but it is good practice to always initialize your variables:

1
2
3
4
int x = 0;
int maxRange = 0;
int minRange = 0;
int randomNum = 0;
that was simpler than I thought! Appreciate the help
Why don't 'professors' teach C++ random number generator and not the C way?

The C++ way for this would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <chrono>
#include <random>

using namespace std;

int main() {

	int x = 0;		// amount of random numbers
	int maxRange = 0;	// random number high
	int minRange = 0;	// random number low

	cout << "What is your random number high? ";
	cin >> maxRange;

	cout << "What is your random number low? ";
	cin >> minRange;

	cout << "How many random numbers do you want? ";
	cin >> x;

	mt19937 gen(chrono::system_clock::now().time_since_epoch().count());
	uniform_int_distribution distrib {minRange, maxRange};

	for (int i = 0; i < x; ++i)
		cout << "The random number is: " << distrib(gen) << endl;
}


Also note that in C++ it is usual to start an iterator at 0 and use < for comparison rather that starting at 1 and using <=
Last edited on
Topic archived. No new replies allowed.