模数和 rand() 如何工作?

How does modulus and rand() work?(模数和 rand() 如何工作?)

本文介绍了模数和 rand() 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直对这个很着迷.

So, I've been nuts on this.

rand() % 6 将始终产生 0-5 之间的结果.

rand() % 6 will always produce a result between 0-5.

但是,当我需要介于两者之间时,可以说是 6-12.

However when I need between, let's say 6-12.

我应该有 rand() % 6 + 6

Should I have rand() % 6 + 6

0+6 = 6.
1+6 = 7.
...
5+6 = 11. ???

如果我想要间隔 6-12,那么我需要 +7 吗?但是,0+7 = 7.什么时候会随机6个?

So do I need to + 7 If I want the interval 6-12? But then, 0+7 =7. When will it randomize 6?

我在这里错过了什么?哪个是在 6 到 12 之间随机数的正确方法?为什么?我好像在这里遗漏了什么.

What am I missing here? Which one is the correct way to have a randomized number between 6 and 12? And why? It seems like I am missing something here.

推荐答案

如果 C++11 是一个选项,那么您应该使用 随机标头 和 uniform_int_distrubution.正如 James 在评论中指出的那样,使用 rand% 有很多问题,包括偏差分布:

If C++11 is an option then you should use the random header and uniform_int_distrubution. As James pointed out in the comments using rand and % has a lot of issues including a biased distribution:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::uniform_int_distribution<int> dist(6, 12);

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

如果您必须使用 rand 那么应该这样做:

if you have to use rand then this should do:

rand() % 7 + 6

更新

使用 rand 的更好方法如下:

A better method using rand would be as follows:

6 + rand() / (RAND_MAX / (12 - 6 + 1) + 1)

我从 C 常见问题解答 中获得了这个,并解释了 如何我得到一定范围内的随机整数? 问题.

I obtained this from the C FAQ and it is explained How can I get random integers in a certain range? question.

更新 2

Boost 也是一种选择:

#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int main()
{
  boost::random::mt19937 gen;
  boost::random::uniform_int_distribution<> dist(6, 12);

  for (int n = 0; n < 10; ++n) {
    std::cout << dist(gen) << ", ";
  }
  std::cout << std::endl ;
}

这篇关于模数和 rand() 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:模数和 rand() 如何工作?

基础教程推荐