[英]How to replicate C++ rand in another language's random function?
I am using an internal language in my company and they only have Random()
that returns a float between 0 and 1. 我在公司中使用内部语言,而且它们只有Random()
返回0到1之间的浮点数。
I need to port a piece of C++ code that use rand()
: 我需要移植一些使用rand()
的C ++代码:
int b = rand() % (i+1);
I looked at the docs, but not sure how I can use my Random()
to generate a number between 0 and i+1
which is what the above code does, right? 我看了看文档,但不确定如何使用我的Random()
生成介于0和i+1
之间的数字,这就是上面的代码,对吗?
I tried multiplying i+1
with Random()
but didn't get the same results, that's why I am not sure if what I am doing is correct. 我尝试将i+1
与Random()
相乘,但是没有得到相同的结果,这就是为什么我不确定我在做什么是否正确的原因。
I expect difference between the results due to different random functions, but still I want to be sure I am translating it correctly. 由于随机函数的不同,我希望结果之间会有所不同,但是我仍然想确保自己正确地翻译了它。
You need to multiply Random()
with i
and not i+1
. 您需要将Random()
乘以i
而不是i+1
。
C++ rand()
returns an integer between 0
and RAND_MAX
but your Random()
returns a float between 0
and 1
, so multiplying the output of Random()
with i
and taking the integer portion of the result will give you an integer in [0,i]
which is what rand() %(i+1)
gives. C ++ rand()
返回一个介于0
和RAND_MAX
之间的整数,但是您的Random()
返回一个介于0
和1
之间的浮点数,因此将Random()
的输出与i
相乘,并取结果的整数部分将为您提供一个[0,i]
的整数[0,i]
是rand() %(i+1)
给出的。
Rand() give you a number between 0 and RAND_MAX, which after applying the mod operator you end up with a number between 0 and i (including i). Rand()为您提供0到RAND_MAX之间的数字,在应用mod运算符后,您最终得到0到i(包括i)之间的数字。
To do the same with Random() you'll need to multiply by ( i+1 ), then take the floor of that (round down): 要对Random()执行相同的操作,您需要乘以(i + 1),然后取下该值(向下取整):
b = floor( Random() * (i+1) )
This will give you a number from 0 to i (including the fence posts) as required. 这将根据需要为您提供从0到i(包括栅栏)的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.