3

I have a simple problem here but no clue how to fix this! I am trying to create a number generator but I only want it to pick a random number from 1-6. No zeros! This question was marked a dup but it shouldn't be because this is C++ NOT C:

srand(static_cast<unsigned int>(time(0)));
int dice = rand()%6;
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
ssj3goku878
  • 745
  • 3
  • 14
  • 43

3 Answers3

13

rand() % 6 gives a number in the range 0..5. Add one to get the range 1..6.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
9

If C++11 is an option you also have std::uniform_int_distribution which is somewhat simpler and less error prone(see rand() Considered Harmful presentation and slides):

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::uniform_int_distribution<> dist(1, 6);

    for( int i = 0 ; i < 10; ++i )
    {
       std::cout << dist(e2) << std::endl ;
    }

    return 0 ;
}

This previous thread Why do people say there is modulo bias when using a random number generator? explains clearly the modulo bias that chris pointed out in his comment.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
4

Almost got it:

int dice = rand()%6 + 1;

John
  • 15,990
  • 10
  • 70
  • 110