Skip to content

Instantly share code, notes, and snippets.

@stungeye
Last active September 14, 2021 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stungeye/213d439931b0e5283cb4f65ad710495d to your computer and use it in GitHub Desktop.
Save stungeye/213d439931b0e5283cb4f65ad710495d to your computer and use it in GitHub Desktop.
Random Number In Range

A simple way to generate a random number in C++ is by using the rand() method.

Here's an application that prints out 10 random numbers from a user specified range:

int randomNumber(const int min, const int max) {
    const int range = max - min + 1;
    return rand() % range + min;
}

int main() {
    // Seed the random number generator with the current time.
    // Without this the random numbers will always be the same.
    srand(time(0)); 
    
    int min, max;
    std::cout << "Lower bound: ";
    std::cin >> min;
    std::cout << "Upper bound: ";
    std::cin >> max;

    std::cout << "Ten numbers between " << min << " and " << max << ":\n";
    for(int i = 0; i < 10; i++) {
        std::cout << randomNumber(min, max) << "\n";
    }
}

Note: The rand() method when combined with a modulus is slightly biased towards smaller numbers, but it will do for our use case.

@edurla
Copy link

edurla commented Sep 14, 2021

  • Without this the random numbers will always been the same. --> "always be the same"
  • The rand() method when combined with a modulus is slightly biased towards smaller numbers, but it will due for our use case. --> "it will do"

@stungeye
Copy link
Author

Thanks @edurla. Fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment