C ++随机数 [英] C++ random numbers

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

问题描述

如下: http://www.fredosaurus.com/notes- cpp / misc / random.html

它提到如果我们要生成一个范围在 1-10 ,我们可以执行以下操作:

It mentions that if we want to generate a random number in the range 1-10, we can do the following:

r =(rand()%10)+ 1;

为什么要添加 1

并且,关于初始化随机数生成器,它提到了以下操作:

And, regarding initializing the random number generator, it mentioned doing the following:

srand(time(0));

你能解释一下吗?

谢谢。

推荐答案

您添加1,因为您想要随机数1-10,而不是0-9,将没有 +1

You add 1, because you want random number 1-10, not 0-9, what will % do without the +1.

例如, 10%10 == 0 9%10 == 9 ,所以这给你0-9。

添加 +1 会将此间隔移动 > 10%10 + 1 == 1 9%10 + 1 == 10

For example, 10 % 10 == 0 and 9 % 10 == 9, so this gives you 0-9.
Adding +1 will "move" this interval to 1-10-> 10 % 10 + 1 == 1 and 9 % 10 + 1 == 10

编辑:很抱歉,您忘记了 srand
rand()生成相同的数字序列,除非你调用 srand 数字生成器具有不同的值,然后调用 rand()。所以,这里 time(0)将当前时间的随机数生成器种子,给你不同的值,你调用 rand )

Sorry, forgot about you srand question. rand() generates the same sequence of numbers, unless you call srand and "seed" the random number generator with different value, before calling rand(). So, here time(0) seeds the random number generator with the current time, that gives you different value for all the times, you call rand()

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

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