吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C/C++ 中的 rand() 和 srand()

C/C++ 中的 rand() 和 srand()

来源:网络 | 更新时间:2022-01-08 20:45:16
rand () rand() 函数在 C/C++ 中用于生成 [0, RAND_MAX) 范围内的随机数。 注意:如果在没有先调用 srand() 的情况下使用 rand() 生成随机数,您的程序将在每次运行时创建相同的数字序列。 句法:
 int rand(void): 
returns a pseudo-random number in the range of [0, RAND_MAX).
RAND_MAX: is a constant whose default value may vary 
between implementations but it is granted to be at least 32767.
假设我们在循环中借助 rand() 在 C 中生成 5 个随机数,那么每次编译和运行程序时,我们的输出必须是相同的数字序列。
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
// This program will create same sequence of
// random numbers on every program run

for(int i = 0; i<5; i++)
printf(" %d ", rand());

return 0;
}
注意:此程序将在每个程序运行时创建相同的随机数序列。  输出 1:
453 1276 3425 89
输出 2:
453 1276 3425 89
输出 n:
453 1276 3425 89
srand() srand() 函数设置生成一系列伪随机整数的起点。如果未调用 srand(),则设置 rand() 种子,就好像在程序启动时调用了 srand(1)。种子的任何其他值都会将生成器设置为不同的起点。  语法: 
void srand( unsigned seed ): 
Seeds the pseudo-random number generator used by rand() with the value seed.
注意:伪随机数生成器只能在调用 rand() 和程序启动之前播种一次。每次您希望生成一批新的伪随机数时,不应重复播种或重新播种。  标准做法是使用调用srand(time(0)) 的结果作为种子。但是, time() 返回一个 time_t 值,该值每次都不同,因此每次程序调用的伪随机数都不同。 
// C program to generate random numbers
#include <stdio.h>
#include <stdlib.h>
#include<time.h>

// Driver program
int main(void)
{
// This program will create different sequence of
// random numbers on every program run

// Use current time as seed for random generator
srand(time(0));

for(int i = 0; i<4; i++)
printf(" %d ", rand());

return 0;
}
注意:此程序将在每个程序运行时创建不同的随机数序列。  输出 1:
453 1432 325 89
输出 2:
8976 21234 45 8975
输出 n:
563 9873 12321 24132
srand() 和 rand() 是如何相互关联的? srand() 设置 rand 用来生成“随机”数字的种子。如果您在第一次调用 rand 之前没有调用 srand,就好像您调用了 srand(1) 将种子设置为一个。  简而言之,srand() — 为 rand() 函数设置种子。 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com