Linux 随机数生成:random 和 rand 函数详解
在 Linux 中,random 和 rand 函数用于生成随机数。
- 生成随机数
要生成随机数,可以使用 random 或 srandom 函数。其中,random 函数用于生成一个随机的整数,srandom 函数用于初始化随机数生成器。
以下示例演示了使用 random 函数生成随机数:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, r;
srand(time(NULL)); // 初始化随机数生成器
for(i=0; i<10; i++)
{
r = random();
printf('%d\n', r);
}
return 0;
}
- 生成指定范围内的随机数
如果需要生成指定范围内的随机数,可以使用 rand 函数和 srand 函数。其中,srand 函数用于初始化随机数生成器,rand 函数用于生成一个 0 到 RAND_MAX 之间的随机整数。
以下示例演示了使用 rand 函数生成指定范围内的随机数:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, r;
srand(time(NULL)); // 初始化随机数生成器
for(i=0; i<10; i++)
{
r = rand() % 10 + 1; // 生成 1 到 10 之间的随机整数
printf('%d\n', r);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/ox3o 著作权归作者所有。请勿转载和采集!