C 庫函數(shù) - rand()

C 標(biāo)準(zhǔn)庫 - <stdlib.h> C 標(biāo)準(zhǔn)庫 - <stdlib.h>

描述

C 庫函數(shù) int rand(void) 返回一個(gè)范圍在 0 到 RAND_MAX 之間的偽隨機(jī)數(shù)。

RAND_MAX 是一個(gè)常量,它的默認(rèn)值在不同的實(shí)現(xiàn)中會(huì)有所不同,但是值至少是 32767。

聲明

下面是 rand() 函數(shù)的聲明。

int rand(void)

參數(shù)

  • NA

返回值

該函數(shù)返回一個(gè)范圍在 0 到 RAND_MAX 之間的整數(shù)值。

實(shí)例

下面的實(shí)例演示了 rand() 函數(shù)的用法。

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

int main()
{
   int i, n;
   time_t t;
   
   n = 5;
   
   /* 初始化隨機(jī)數(shù)發(fā)生器 */
   srand((unsigned) time(&t));

   /* 輸出 0 到 49 之間的 5 個(gè)隨機(jī)數(shù) */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
  return(0);
}

讓我們編譯并運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:

38
45
29
29
47

C 標(biāo)準(zhǔn)庫 - <stdlib.h> C 標(biāo)準(zhǔn)庫 - <stdlib.h>