请教:不知道怎样才能提高随机数生成的随机性?

joyzm 2003-10-27 11:33:52
我用时间做种子,想在循环中实现[0,1]之间任意随机数(包括小数)的生成;由于是以时间做种子,所以生成的系列值几乎没有变化,不能实现对程序预期期望作用的目的?
不知道该怎么改进才能提高生成数的随机性?
谢谢
...全文
202 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
cfpp1234 2003-10-27
  • 打赏
  • 举报
回复
// 如果你是寫Console application,你要在VC++的選單Project下的Setting裹
// 的General Tab,在Microsoft Foundation Classes中選Use MFC inShare DLL
// 再加入#include <afx.h>.這些要先設定好.
//
// 但如果你寫的本身就是MFC application(window program),就不須要以上的
// 設定
//
// 以下是RandomStart与Random函數,只要在程式的開始調用RandomStart,
// 之後再調用Random就可,我做了一個main以作試範

#include <iostream>
#include <time.h>
#include <afx.h>
using namespace std ;

void RandomStart()
{
unsigned int sd = (unsigned int)time( NULL ) ;
int sf = sd % 5 ;
if ( sf == 0 )
sf = 1 ;
else
sf += 1 ;

sd *= sf ;

unsigned int td = (unsigned int)GetTickCount() ; // Window API
int tf = sd % 4 ;
if ( tf == 0 )
tf = 1 ;
else
tf += 1 ;

sd *= tf ;

srand( sd );
}


template < class Type >
inline Type Random( const Type start , const Type end )
{
double rt = (double)rand() / (double)RAND_MAX ;
return (Type)( start + (end - start) * rt ) ;
}

int main()
{
RandomStart() ;

for ( int i=0; i<10; i++ )
printf("%f\n",Random(0.0,1.0)) ;

return 0 ;
}
Andy84920 2003-10-27
  • 打赏
  • 举报
回复
srand(time(0));
rand();

搞定这两个函数就OK了!

rand()是产生随机数函数。不过如果不种种子的话就不会有真正的随机!
tass 2003-10-27
  • 打赏
  • 举报
回复
up
453 2003-10-27
  • 打赏
  • 举报
回复
/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

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

void main( void )
{
int i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}


Output

6929
8026
21987
30734
20587
6699
22034
25051
7988
10104

这是MSDN中的一个例子,也是用时间做种子的,看看你的以时间做种子会不会有什么问题
daizh 2003-10-27
  • 打赏
  • 举报
回复
你看一下已往的关于随机数的生成问题的帖子。
HostOOP 2003-10-27
  • 打赏
  • 举报
回复
把你的时间精确到微秒就行了。实在不行,精确到秒也有效啊
bluedodo 2003-10-27
  • 打赏
  • 举报
回复
问题解决就好
lemon520 2003-10-27
  • 打赏
  • 举报
回复
顶!
carbon107 2003-10-27
  • 打赏
  • 举报
回复
srand()种子是非常重要的
joyzm 2003-10-27
  • 打赏
  • 举报
回复
谢谢!
问题得到圆满解决!

70,018

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧