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!!
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;
}
}
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;
#include <iostream>
#include <chrono>
#include <random>
usingnamespace 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 <=