- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - rand() 函式
C 的stdlib 庫的rand() 函式用於返回範圍在 0 到 RAND_MAX 之間的偽隨機數。
RAND_MAX 表示 rand() 函式可以返回的最大值,其預設值可能因 C 庫的實現而異。但它保證至少為 32767。
語法
以下是 rand() 函式的 C 庫語法:
int rand(void)
引數
此函式不接受任何引數。
返回值
此函式返回一個介於 0 到 RAND_MAX 之間的整數值。
示例 1
在本例中,我們建立一個基本的 C 程式來演示 rand() 函式的使用。
#include <stdio.h>
#include <stdlib.h>
int main() {
// store the random value
int rand_value = rand();
// display the random value
printf("Random Value: %d\n", rand_value);
return 0;
}
以下是輸出:
Random Value: 1804289383
示例 2
下面的 C 程式用於使用 rand() 函式在一定範圍內顯示隨機數。
#include <stdio.h>
#include <stdlib.h>
int main() {
// display the random value
int i;
for(i=1; i<=5; i++)
{
printf("%d ", rand());
}
return 0;
}
輸出
以下是輸出:
1804289383 846930886 1681692777 1714636915 1957747793
示例 3
讓我們再建立一個示例,我們正在建立一個 C 程式來生成將是 10 的倍數的隨機數。
#include <stdio.h>
#include <stdlib.h>
int main() {
// display the random value
int num = 10;
int i;
for(i=1; i<=6; i++)
{
printf("%d ", rand()%num);
}
return 0;
}
輸出
以下是輸出:
3 6 7 5 3 5
廣告