random函数用法c语言
时间: 2023-08-02 19:35:28 浏览: 142
在C语言中,可以使用stdlib.h库中的`rand()`函数来生成伪随机数。`rand()`函数返回一个0到RAND_MAX之间的整数,其中RAND_MAX是一个常量,其值至少为32767。
如果需要生成一定范围内的随机数,可以使用如下公式:
```c
int random_num = rand() % (max - min + 1) + min;
```
其中`min`和`max`分别是随机数的最小值和最大值,`rand() % (max - min + 1)`可以生成0到`max - min`之间的随机数,再加上`min`即可生成`min`到`max`之间的随机数。
需要注意的是,在使用`rand()`函数之前,需要调用`srand()`函数来初始化随机数发生器。如果没有调用`srand()`函数,每次生成的随机数序列都是相同的。在`srand()`函数中可以传入一个随机数种子,以便生成不同的随机数序列。
下面是一个简单的示例代码,可以生成10个0到9之间的随机数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// 初始化随机数发生器
srand(time(NULL));
// 生成随机数
for (int i = 0; i < 10; i++) {
int random_num = rand() % 10;
printf("%d ", random_num);
}
printf("\n");
return 0;
}
```
需要注意的是,`rand()`函数生成的是伪随机数,其随机性并不十分强,如果需要更加随机的生成方式,可以使用硬件随机数生成器或者第三方库。
阅读全文
相关推荐


















