如何生成一个大于RAND_MAX的随机整数 [英] How to generate a random integer that is bigger than RAND_MAX
问题描述
如何生成一个大于RAND_MAX的随机整数。
RAND_MAX是rand函数的最大值。等于0x7fff
How to generate a random integer that is bigger than RAND_MAX.
the RAND_MAX is the max of rand function. and equal to 0x7fff
推荐答案
?μ·é£?写道:
如何生成一个大于RAND_MAX的随机整数。
RAND_MAX是rand函数的最大值。等于0x7fff
How to generate a random integer that is bigger than RAND_MAX.
the RAND_MAX is the max of rand function. and equal to 0x7fff
这是一个实施质量问题。我使用的实现是使用RAND_MAX等于0x7fffffff。
无论如何你可以使用提升随机库,顺便说一句
接受C ++ 0x标准草案。
This is a quality of implementation issue. The implementation I am
using has RAND_MAX equal to 0x7fffffff.
Anyway you can use the boost random library which was by the way
accepted into the draft C++0x standard.
?μ·é£?写道:
如何生成一个大于RAND_MAX的随机整数。
RAND_MAX是rand函数的最大值。等于0x7fff
How to generate a random integer that is bigger than RAND_MAX.
the RAND_MAX is the max of rand function. and equal to 0x7fff
如果RAND_MAX = 0x7fff ...则可以使用:
unsigned int r = ~rand ();
如果(我认为很常见)RAND_MAX是最大的[signed] int(例如,16位的
0x7fff,32位的0x7fffffff) ,然后你得到一个随机数
从RAND_MAX + 1到2 * RAND_MAX - 1(0x8000 ......到0xffff ...)包含。
证明留给读者作为练习。 :)
HTH,
斯图尔特
If RAND_MAX = 0x7fff... then you can use:
unsigned int r = ~rand();
If (as I believe is common) RAND_MAX is the largest [signed] int (e.g.
0x7fff in 16bit, 0x7fffffff in 32 bit), then you get a random number
from RAND_MAX + 1 to 2 * RAND_MAX - 1 (0x8000... to 0xffff...) inclusive.
Proof left as an exercise to the reader. :)
HTH,
Stewart
" ??"写道:
"??" wrote:
如何生成一个大于RAND_MAX的随机整数。
RAND_MAX是rand函数的最大值。并且等于0x7fff
How to generate a random integer that is bigger than RAND_MAX.
the RAND_MAX is the max of rand function. and equal to 0x7fff
使用移位运算符并将两个(或更多)调用的结果添加到rand()
到更大的类型。 rand()返回随机*位*的集合。
Use a shift operator and add the result of two (or more) calls on rand()
into a larger type. rand() returns a collection of random *bits*.
这篇关于如何生成一个大于RAND_MAX的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!