C 语言中的 randomize 和 srand 函数有什么作用?
如果我们在程序中生成随机数,那么控制该系列数字非常有必要。
randomize() 和 srand() 函数用于设置随机数生成器的种子。
为随机数生成器指定起始数字的过程称为设置生成器的种子。
randomize() 使用 PC 时钟来生成一个随机种子。
srand() 允许我们指定随机数生成器的起始值。
程序
以下是关于 rand 的 C 程序 −
#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; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
您将看到以下输出 −
1919778910 1203408690 1755813469 1976428341 37040990 1849384103 986990763 2040061815 391541163 1718314135
广告