溫馨提示×

c語言怎么連續(xù)生成不同隨機數(shù)

小億
201
2023-11-29 23:52:11
欄目: 編程語言

在C語言中,可以使用標(biāo)準(zhǔn)庫中的rand()函數(shù)來生成隨機數(shù)。要生成不同的隨機數(shù),可以結(jié)合時間函數(shù)time()來設(shè)置隨機數(shù)種子。以下是一個示例代碼:

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

int main() {
    int i;
    // 設(shè)置隨機數(shù)種子為當(dāng)前時間
    srand(time(NULL));
    
    // 生成10個不同的隨機數(shù)
    for (i = 0; i < 10; i++) {
        int num = rand();
        printf("%d\n", num);
    }
    
    return 0;
}

在上述示例中,srand(time(NULL))用于設(shè)置隨機數(shù)種子,time(NULL)函數(shù)返回當(dāng)前時間的秒數(shù)。每次程序運行時,種子都會不同,從而生成不同的隨機數(shù)序列。然后使用rand()函數(shù)生成隨機數(shù),并輸出到屏幕上。

0