简体   繁体   中英

c++ user defined random number generator

I am having some trouble generating 10 random numbers between a user defined range.

I have this so far:

int minimum, maximum, randNum;

cout << "Hello, please insert the smallest number for your range of random numbers" << endl;
cin >> minimum;
cout << "Please insert your largest number for your range of random numbers" << endl;
cin >> maximum;

srand (time(NULL));
randNum = rand()%(maximum-minimum)+minimum;

Not really sure where to go from here. Any help is appreciated, thanks!

Here you go:

#include <iostream>
#include <random>

int main() {
    int minimum, maximum;
    std::cin >> minimum >> maximum;

    // Create a random number generator
    std::random_device rd;
    std::mt19937 gen(rd());

    // We want random numbers within [minimum, maximum]
    std::uniform_int_distribution<> dis(minimum, maximum);

    // Print 10 random numbers    
    for (int i=0; i<10; ++i)
        std::cout << dis(gen) << "\n";
}

You should just make a simple loop around your random number generating code, pushing each value into a vector. Have the condition of the loop be like so:

for(int i =0; i < 10; ++i)

Overall you should have something like this:

srand(time(NULL));
vector<int> vec;
for(int i = 0; i < 10; ++i){
    vec.push_back(rand() % max + min);
}

All 10 numbers will be in your vector. Or some method along those lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM