C stdlib rand() 函式
示例
顯示 10 個介於 1 和 100 之間的隨機數
// Initialize the randomizer using the current timestamp as a seed
// (The time() function is provided by the <time.h> header file)
srand(time(NULL));
// Generate random numbers
for (int i = 0; i < 10; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
自己動手試一試 »
定義和用法
rand()
函式返回一個非負整數。
此函式生成的數字是偽隨機的,這意味著如果掌握足夠的資訊,就有可能預測它們。為了使數字看起來更隨機,應該使用 srand()
函式,併為每次程式執行時提供一個不同的值來播種。
rand()
函式定義在 <stdlib.h>
標頭檔案中。
語法
rand()
技術詳情
返回 | 一個表示隨機整數的 int 值。 |
---|