# 哪位高手知道rand()实现方法？

fanne 2003-12-12 10:07:22
c++中产生随机数可用：
#include <cstdlib>
.............
srand(int m);
int n=rand()%m;
............

...全文
166 11 打赏 收藏 举报

11 条回复

cxjddd 2003-12-13
《The GNU C Library》里说的，大概如下：

Y = (a * X + c) mod m
a，c，m 都是常数

a = 0x5DEECE66D = 25214903917
c = 0xb = 11
m = 2^48

__int64 rand ()
{
static __int64 r = 0;
const __int64 a = 25214903917;
const __int64 c = 11;
const __int64 m = 1 << 48;
r = (r * a + c) % m;
return r;
}
• 打赏
• 举报

raygtr 2003-12-13
#include < iostream.h >
#include < iomanip.h >
#include < stdlib.h >
#include < time.h >
void main()
{
const int arraySize =7;
int face,frequency[ arraySize ] ={0};
srand( time(NULL));
for(int roll= 1;roll <=6000; roll++)
++frequency[1+rand()%6];

cout<<"Face "<<setw(13) <<"Frequency"<<endl;
for(int facce =0; facce<arraySize; facce++)
cout<<facce<<endl<<frequency[facce]<<endl;

}
• 打赏
• 举报

lyr311 2003-12-13

• 打赏
• 举报

cpsoft 2003-12-13

• 打赏
• 举报

zming 2003-12-13

• 打赏
• 举报

smalltalk 2003-12-13

static long holdrand = 1L;

/***
*void srand(seed) - seed the random number generator
*
*Purpose:
* Seeds the random number generator with the int given. Adapted from the
* BASIC random number generator.
*
*Entry:
* unsigned seed - seed to seed rand # generator with
*
*Exit:
* None.
*
*Exceptions:
*
*******************************************************************************/

void __cdecl srand (
unsigned int seed
)
{
holdrand = (long)seed;
}

/***
*int rand() - returns a random number
*
*Purpose:
* returns a pseudo-random number 0 through 32767.
*
*Entry:
* None.
*
*Exit:
* Returns a pseudo-random number 0 through 32767.
*
*Exceptions:
*
*******************************************************************************/

int __cdecl rand (
void
)
{
return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
}
• 打赏
• 举报

zhukeke 2003-12-12

• 打赏
• 举报

fanne 2003-12-12

• 打赏
• 举报

cpsoft 2003-12-12

• 打赏
• 举报

layman2008 2003-12-12

• 打赏
• 举报

redhat_xu 2003-12-12
#include<iostream.h>
#include <stdlib.h>
void main()
{
int i;
double j;
randomize();//随机函数初始化
for( i = 0; i < 30;i++ )
{
j=(double)(rand()/(double)RAND_MAX); //求随机值
cout<<j<<endl;
}
}

• 打赏
• 举报

6.1w+

C++ 语言相关问题讨论，技术干货分享，前沿动态等

2003-12-12 10:07