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;
4

3 回答 3

13

rand() % 6给出范围内的一个数字0..5。加一得到范围1..6

于 2013-08-08T03:52:52.257 回答
9

如果 C++11 是一个选项,您还可以选择std::uniform_int_distribution更简单且不易出错的选项(请参阅rand() 被认为是有害的演示文稿幻灯片):

#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为什么人们说使用随机数生成器时存在模偏差?清楚地解释了克里斯在评论中指出的模数偏差。

于 2013-08-08T04:01:23.650 回答
4

差不多明白了:

int dice = rand()%6 + 1;

于 2013-08-08T03:54:15.867 回答