问题描述
我想获得一个0到1之间的随机数。
以下代码可以工作,但在我看来是一个小小的
尴尬。有没有更好的解决方案。
double rnd;
int integerRnd;
srand(static_cast< unsigned>(time(NULL) )));
for(int i = 0; i< 9; ++ i){
// rand()返回0到32767之间的值
rnd = 10000./ rand();
//商的整数部分
integerRnd = rnd;
//每个随机数,形式为0.xxx
rnd - = integerRnd;
cout<< rnd<< endl;
}
将[0,n]范围内的值减少到范围[0,1}
的常用方法是除以n + 1。如果你希望1在最终范围内,则除以n
。
-
Pete Becker
Dinkumware,Ltd。()
将[0,n]范围内的值减少到范围[0,1}
的常用方法是除以n + 1。如果你希望1在最终范围内,则除以n
。
忘了提及,以下评论:
// rand()返回0到32767之间的值
不正确。兰德的一些实现做到了,其他人不做。看看
了。
-
Pete Becker
Dinkumware,有限公司()
I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.
double rnd;
int integerRnd;
srand(static_cast<unsigned>(time(NULL)));
for (int i = 0; i < 9; ++i) {
// rand() returns a value from 0 to 32767
rnd = 10000. / rand();
// integer part of quotient
integerRnd = rnd;
// every random number in the form of 0.xxx
rnd -= integerRnd;
cout << rnd << endl;
}
The usual way to reduce values in the range [0, n) to the range [0, 1)
is to divide by n+1. If you want 1 to be in the final range, divide by n
instead.
--
Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
The usual way to reduce values in the range [0, n) to the range [0, 1)
is to divide by n+1. If you want 1 to be in the final range, divide by n
instead.
Forgot to mention, the following comment:
// rand() returns a value from 0 to 32767
is incorrect. Some implementations of rand do that, others don''t. Look
it up.
--
Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
这篇关于随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!