Latest web development tutorials

C 庫函數– srand()

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>

描述

C庫函數void srand(unsigned int seed)播種由函數rand使用的隨機數發生器。

聲明

下面是srand() 函數的聲明。

void srand(unsigned int seed)

參數

  • seed --這是一個整型值,用於偽隨機數生成算法播種。

返回值

該函數不返回任何值。

實例

下面的實例演示了srand() 函數的用法。

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

int main()
{
   int i, n;
   time_t t;
   
   n = 5;
   
   /* 初始化随机数发生器 */
   srand((unsigned) time(&t));

   /* 输出 0 到 50 之间的 5 个随机数 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
  return(0);
}

讓我們編譯並運行上面的程序,這將產生以下結果:

38
45
29
29
47

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>