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++?

Community
  • 1
  • 1
John
  • 1,556
  • 4
  • 26
  • 42
  • [What have you tried?](http://whathaveyoutried.com) – Matt Ball Oct 04 '12 at 19:22
  • 1
    What have you tried? Googling "generate random number C++" should get you started. – Blender Oct 04 '12 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()`. – bames53 Oct 04 '12 at 21:18

2 Answers2

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

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
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;
}
halex
  • 16,253
  • 5
  • 58
  • 67