随机数

伪随机数

需要#include <stdlib.h>,用法【无参数】:

1
int rand (void);    // 随机数的范围:0 ~ RAND_MAX

注意:每次开机后,使用rand()函数生成的随机数是固定的。

示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include <stdlib.h>

int main()
{
int randomNum = rand(); // rand()函数返回值为int【0 ~ RAND_MAX】
printf("随机数:%d", randomNum);

return 0;
}

生成真随机数

需要 #include <stdlib.h>#include <time.h>,用法【有参数】:

1
void srand (unsigned int seed);    // 重新播种

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
srand((unsigned)time(NULL)); // 以时间作为种子
int randomNumber = rand();
printf("真随机数:%d", randomNumber);

return 0;
}

指定范围随机数

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
srand((unsigned)time(NULL)); // 以时间作为种子
int randomNumber = rand() % 100; // 范围:0-99
printf("指定范围随机数:%d", randomNumber);

return 0;
}

生成多个随机数【循环外播种一次即可】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
srand((unsigned)time(NULL)); // 以时间作为种子
for (int i = 0; i < 10; i++)
{
int randomNumber = rand();
printf("%d ", randomNumber);
}

return 0;
}