
如果我们在程序中生成随机数,有必要控制数字的序列。
randomize()和srand()函数用于种子随机数生成器。
分配随机数生成器起始数字的过程称为种子生成器。
randomize()使用PC的时钟产生一个随机种子。
立即学习“C语言免费学习笔记(深入)”;
srand()允许我们指定随机数生成器的起始值。
下面是C语言中关于rand的程序:
演示
#include<stdio.h>
int main(){
// create same sequence of
// random numbers on every time the program runs
for(int i = 0; i<10; i++)
printf(" %d ", rand());
return 0;
}您将看到以下输出 −
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421
以下是关于srand的C程序:
在线演示
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int main(){
// create different sequence of
// random numbers on every time the program runs
// It Use current time as seed for random generator
srand(time(0));
for(int i = 0; i<10; i++)
printf(" %d ", rand());
return 0;
}您将看到以下输出 −
1919778910 1203408690 1755813469 1976428341 37040990 1849384103 986990763 2040061815 391541163 1718314135
以上就是随机化和srand函数在C语言中的用途是什么?的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号