温馨提示×

c语言随机数如何生成

小亿
84
2024-01-18 21:46:01
栏目: 编程语言

在C语言中,可以使用rand()函数来生成随机数。但是,在每次程序运行时,生成的随机数序列是相同的。为了使得每次生成的随机数序列都不同,可以使用srand()函数设置一个种子值,通常使用当前时间作为种子值。

以下是一个生成随机数的示例代码:

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

int main() {
    int i;
    int num;

    // 设置种子值
    srand(time(NULL));

    // 生成随机数
    for (i = 0; i < 10; i++) {
        num = rand();
        printf("%d\n", num);
    }

    return 0;
}

在上述代码中,srand(time(NULL))函数将当前时间作为种子值,然后使用rand()函数生成10个随机数,并将其打印出来。每次运行程序时,生成的随机数序列都会不同。

0