rand ( ) 和 srand ( )【C語言庫函數原始碼】

來源:互聯網
上載者:User

【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 <time.h>

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;

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.