- #1
ChrisVer
Gold Member
- 3,378
- 464
Hi. I am trying to create a program that I will give the maximum range (1,...,max) from which to generate random numbers, and make it generate N=maxgen random numbers (which later I can use for example in another program). Below you can see the code I wrote:
Mod note: I formatted the code above using [ code ] tags.My problem is that the program doesn't generated N=maxgen random numbers, but it generates only 1 number for maxgen times (so I think something is wrong with my second for loop). Any idea?
For eg max=5 and maxgen=10 , I get 10 times the number 4. Whereas my idea is to get something like: 1,5,4,3,5,2,4,1,4,2 (ten random numbers from 1 to 5).
C:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>
using namespace std;
int main(){
int max,maxgen;
cout<< "Please give the number of maximum = " ; //max for the range of generated numbers (1,...,max)
cin >> max ;
cout << endl << "Please give the number of generated numbers = " ;
cin >> maxgen;
cout << endl;
vector<int> random_no; //an empty vector to take in its elements the random numbers
for(int j=0; j<= maxgen; ++j){ // to print the generated numbers
for(int a=0; a<=max; ++a){ //to generate at each element the random numbers
srand(time(0));
random_no.push_back((rand () % max) + 1);
}
cout << random_no.at(j) << endl;
}
system("pause");
return 0;
}
For eg max=5 and maxgen=10 , I get 10 times the number 4. Whereas my idea is to get something like: 1,5,4,3,5,2,4,1,4,2 (ten random numbers from 1 to 5).
Last edited by a moderator: