# `rand`

## 语法

``````int rand(void);
``````

## 注解

`rand` 函数返回从 0 到 `RAND_MAX` (32767) 范围内的一个伪随机整数。 在调用 `rand` 之前，使用 `srand` 函数对伪随机数生成器生成种子。

`rand` 函数生成已知序列，不适合用作加密函数。 若要生成加密型更安全的随机数，请使用 `rand_s` 或使用 `<random>` 中 C++ 标准库中声明的函数。

## 要求

`rand` `<stdlib.h>`

## 示例

``````// crt_rand.c
// This program seeds the random-number generator
// with a fixed seed, then exercises the rand function
// to demonstrate generating random numbers, and
// random numbers in a specified range.

#include <stdlib.h> // rand(), srand()
#include <stdio.h> // printf()

void SimpleRandDemo(int n)
{
// Print n random numbers.
for (int i = 0; i < n; i++)
{
printf("  %6d\n", rand());
}
}

void RangedRandDemo(int range_min, int range_max, int n)
{
// Generate random numbers in the interval [range_min, range_max], inclusive.

for (int i = 0; i < n; i++)
{
// Note: This method of generating random numbers in a range isn't suitable for
// applications that require high quality random numbers.
// rand() has a small output range [0,32767], making it unsuitable for
// generating random numbers across a large range using the method below.
// The approach below also may result in a non-uniform distribution.
// More robust random number functionality is available in the C++ <random> header.
// See https://learn.microsoft.com/cpp/standard-library/random
int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min;
printf("  %6d\n", r);
}
}

int main(void)
{
// Seed the random-number generator with a fixed seed so that
// the numbers will be the same every time we run.
srand(1792);

printf("Simple random number demo ====\n\n");
SimpleRandDemo(10);
printf("\nRandom number in a range demo ====\n\n");
RangedRandDemo(-100, 100, 100000);
}```

```Output
Simple random number demo ====

5890
1279
19497
1207
11420
3377
15317
29489
9716
23323

Random number in a range demo ====

-82
-46
50
77
-47
32
76
-13
-58
90
``````