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

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

问题描述



rand()%6总是产生一个0-5之间的结果。

$ b $



我应该有rand()%6 + 6

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

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



我在这里缺少什么?哪一个是正确的方法有一个随机的数字在6和12之间?为什么?

解决方案

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

  #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 那么应该这样做:

  rand()%7 + 6 

更新 p>

使用 rand 的更好方法如下:

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

$ b b

我从 C常见问题中获得了这一点,如何在一定范围内获取随机整数?问题。



更新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;
}


So, I've been nuts on this.

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

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

Should I have rand() % 6 + 6

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

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

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.

解决方案

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

if you have to use rand then this should do:

rand() % 7 + 6

Update

A better method using rand would be as follows:

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

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

Update 2

Boost is also an option:

#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()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆