中央领导古牧:vc++中的随机函数是什么?怎么用的?

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/28 14:41:01
例如产生0-255的随机正整数怎么做?

VC++中,产生随机数有一个函数
int rand(void); // #include <stdlib.h>
是随机产生一个0到RAND_MAX的整数
但要产生0-255,可能要自己写函数实现了。

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

/*该函数缺陷:只能取正整数的随机值*/
int myRand(int iMax)
{
assert( iMax >0 );
int iRand;

iRand = rand();

if ( iRand <= iMax )
return iRand;
else
iRand = iRand%iMax;

return iRand;
}

void main( void )
{
for( int i = 0; i < 10;i++ )
{
printf(" %6d\n", myRand(255));
}
}

将得到的值转为浮点型
然后除以RAND_MAX再乘以255然后转为整型就是了