rand()函数 [英] rand() function in c++

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

问题描述

我不太确定c ++中的函数如何工作:

  int rand_0toN1(int n){
return rand()%n;另一个教程在互联网上说要获得一个范围之间的一个随机数你需要的做一些不同的事情,有一个范围内的第一个数字,n是范围内的术语数:

  int number = a + rand()%n; 

我读过,它应该返回一个介于0和n-1之间的随机数,但是怎么做呢?我明白%意味着分割和给剩余部分(所以5%2将是1),但是最终如何得到一个0和n-1之间的数字?感谢您的帮助理解这一点。我想我不明白什么rand()函数返回。

解决方案

n > 0除法的模数(余数)总是在范围[0 , n );这是模运算的基本属性。



a + rand()%n 范围[0, n ),除非 a = 0;它会在[ a n + a 范围内返回 int / p>

请注意,这个秘诀不是一般返回均匀分布的整数


i am not quite sure how this function in c++ works:

int rand_0toN1(int n) {
    return rand() % n;
}

Another tutorial on internet says to get a random number between a range you need to do something different however, with a being first number in range and n is number of terms in range:

int number = a + rand( ) % n;

I have read that it is supposed to return a random number between the value of 0 and n-1, but how does it do that? I understand that % means divide and give the remainder (so 5 % 2 would be 1) but how does that end up giving a number between 0 and n-1? Thanks for help in understanding this. I guess i don't understand what the rand() function returns.

解决方案

The modulo (remainder) of division by n > 0 is always in the range [0, n); that's a basic property of modular arithmetic.

a + rand() % n does not return a number in the range [0, n) unless a=0; it returns an int in the range [a, n + a).

Note that this trick does not in general return uniformly distributed integers.

这篇关于rand()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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