0

Possible Duplicate:
How to generate a random number from within a range - C

I want to generate a random number between 0 and 4 inclusively. How can I do this in c++?

3
  • What have you tried? Commented Oct 4, 2012 at 19:22
  • 1
    What have you tried? Googling "generate random number C++" should get you started. Commented Oct 4, 2012 at 19:22
  • This isn't a duplicate of that question about C because this question is about C++. In the current version of C++ the correct answer will obviously not involve rand(). Commented Oct 4, 2012 at 21:18

2 Answers 2

6

You could call std::rand(), usning the modulo operator to limit the range to the desired one.

std::rand()%5

You can also have a look at the new C++11 random number generation utilities

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I figured I'd at least have to include another library
3

Just for completeness I show you a C++11 solution using the new random facility:

#include <random>
#include <ctime> 

int main() {
    std::minstd_rand generator(std::time(0)); 
    std::uniform_int_distribution<> dist(0, 4);
    int nextRandomInt = dist(generator);
    return 0;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.