gpt4 book ai didi

c - srand(时间(NULL)) 函数

转载 作者:行者123 更新时间:2023-11-30 18:46:10 24 4
gpt4 key购买 nike

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

int main( void){

int x = rand()%100;
printf("%d\n", x);
return 0;
}

上面的代码正确生成了一个随机数。它是否正确?但是,其他来源始终包括库和 srand(time(NULL))。为什么我们必须包含include库和srand(time(NULL))?有什么理由要包括在内吗?

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

int main( void){
srand(time(NULL));
int x = rand()%100;
printf("%d\n", x);
return 0;
}

最佳答案

因为如果多次运行此代码,您将得到相同的结果! (此外,rand() 在每次运行中返回相同的结果)。因此,您可以在每次运行代码时初始化随机种子,以通过 srand 获得不同的随机结果。使用time(NULL)通过srand设置不同的随机种子。

关于c - srand(时间(NULL)) 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com