C stdlib srand() 函数
示例
显示 10 个介于 1 和 100 之间的随机数
// Initialize the randomizer using the current timestamp as a seed
// (The time() function is provided by the <time.h> header file)
srand(time(NULL));
// Generate random numbers
for (int i = 0; i < 10; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
自己动手试一试 »
定义和用法
srand()
函数使用种子初始化 rand()
函数。种子指定 rand()
函数将遵循哪个数字序列。这意味着相同的种子将始终产生相同的随机数序列。
srand()
函数定义在 <stdlib.h>
头文件中。
语法
srand(unsigned int seed);
参数值
参数 | 描述 |
---|---|
seed | 指定 rand() 函数将遵循哪个数字序列的数字。 |
更多示例
示例
显示相同的随机数序列两次
// Initialize the randomizer with a fixed value
srand(10000);
// Generate 5 random numbers
for (int i = 0; i < 5; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
printf("\n");
// Initialize the randomizer with the same value
srand(10000);
// Generate 5 random numbers
for (int i = 0; i < 5; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
自己动手试一试 »