龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

随机数算法

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
/*1.从同一个种子开始*/ #include #include static unsigned long int next=1; int rand0(void) { next=next*1103515245+12345; return (unsigned int)(next/65536)%32768; } int main(void) { int count; for(count=0;count printf("%hd ",rand0());

/*1.从同一个种子开始*/

  #include

  #include

  static unsigned long int next=1;

int rand0(void)

  {

  next=next*1103515245+12345;

  return (unsigned int)(next/65536)%32768;

  }

int main(void)

  {

  int count;

for(count=0;count<5;count++)

   printf("%hd

",rand0());

  getch();

  return 0;

  }

/*2.重置种子*/

  #include

  #include

  static unsigned long int next=1;

int rand1(void)

  {

  next=next*1103515245+12345;

  return (unsigned int)(next/65536)%32768;

  }

void srand1(unsigned int seed)

  {

  next=seed;

  }

int main(void)

  {

  int count;

  unsigned int seed;

printf("please input seed:");

  scanf("%u",&seed);

  srand1(seed);

  for(count=0;count<5;count++)

   printf("%hd

",rand1());

  getch();

  return 0;

  }

/*3.利用利用时钟产生种子

  ANSI C程序库提供了rand()函数来产生随机数;

  ANSI C程序库提供了srand()函数来产生种子;

  ANSI C程序库提供了time()函数返回系统时间。

  */

  #include

  #include

  #include

  #include

  #include

int main(void)

{

   int i;

   time_t t;

   clrscr();

   t = time(NULL);

   srand((unsigned) t);

   for(i=0; i<10; i++) printf("%d

", rand()%10);

   getch();

   return 0;

  }

  

  

精彩图集

赞助商链接