Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1396175
  • 博文数量: 143
  • 博客积分: 10005
  • 博客等级: 上将
  • 技术积分: 1535
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-23 17:25
个人简介

淡泊明志 宁静致远

文章分类

全部博文(143)

文章存档

2011年(2)

2009年(1)

2007年(22)

2006年(118)

我的朋友

分类: C/C++

2006-12-10 19:08:24

C语言库函数源代码】

【本程序在Dev C++ 4.9.9.2 下编译通过】

/*

   这两个函数是C库中产生随机数的程序。你需要先

   使用srand()函数赋随机数种子值。然后再使用

   rand()函数来产生随机数。但是产生随机数的算法

   较简单,srandom()和random()函数是对这两个函数

   的改良,用法也很类似。

*/

#define RANDOM_MAX 0x7FFFFFFF

static long my_do_rand(unsigned long *value)

{

/*

      这个算法保证所产生的值不会超过(2^31 - 1)

这里(2^31 - 1)就是 0x7FFFFFFF。而 0x7FFFFFFF

      等于127773 * (7^5) + 2836,7^5 = 16807。

      整个算法是通过:t = (7^5 * t) mod (2^31 - 1)

      这个公式来计算随机值,并且把这次得到的值,作为

下次计算的随机种子值。

   */

   long quotient, remainder, t;

 

   quotient = *value / 127773L;

   remainder = *value % 127773L;

   t = 16807L * remainder - 2836L * quotient;

 

   if (t <= 0)

      t += 0x7FFFFFFFL;

  return ((*value = t) % ((unsigned long)RANDOM_MAX + 1));

}

static unsigned long next = 1;

int my_rand(void)

{

   return my_do_rand(&next);

}

void my_srand(unsigned int seed)

{

   next = seed;

}

#include

int main()

{

   int i;

  

   my_srand((unsigned)(time(NULL)));

   for(i=0;i<100;i++)

   {

      if(i % 10 == 0)

         printf("\n");

      printf("%d\t",my_rand()%99+1);

   }

   system("pause");

   return 0;

}

阅读(11353) | 评论(6) | 转发(0) |
给主人留下些什么吧!~~

ammana_babi2008-04-03 10:14:27

srand()函数用来赋随机数种子值。 rand()函数来产生随机数。 假设我们有一个大小为100的数组,而数组的每个元素的值需要随即产生。那么你可以参考下面的代码。 #include int main() { int i,buffer[100]; srand(time(NULL)); //Initialize the random seed for( i=0; i<100; i++ ) buffer[i] = rand(); //Get random value for( i=0; i<100; i++ ) //Print the random value buffer { if( i%10 == 0 ) printf("\n"); printf("%d\t", buffer[i]); } system("pause"); return 0; } 为什么要用srand(time(NULL)); //Initialize the random seed 来初

chinaunix网友2008-04-02 01:54:37

例如说吧:a=rand()%90+10是指什么呢??? srand与rand有什么关系呢??? 如何使用呢??? 希望能有一个好的答复!!!谢谢啦!!!!

chinaunix网友2008-04-02 01:50:59

什么意思呀 ???? 我想知道srand()到底是指什么呢?? 若是一个函数,那么它是什么特性,什么使用呢???