C语言基础-随机数

C语言基础-随机数

随机数

在很多编程场景中,我们都需要用到随机数,例如抽奖程序、游戏机制、测试数据等。在 C 语言中,我们可以使用标准库函数 rand() 来生成随机数。

一、rand():生成随机整数

函数原型:

#include

int rand(void);

返回一个 [0, RAND_MAX] 之间的整数(RAND_MAX 通常为 32767);

每次运行程序生成的随机数默认是固定的序列。

示例:

#include

#include

int main(void) {

int r = rand();

printf("随机数:%d\n", r);

return 0;

}

多次运行上面的代码,输出结果是一样的 —— 这是因为没有设置“种子”。

二、srand():设置随机数种子

为了让每次程序运行时生成的随机数不同,需要使用 srand() 设置随机种子。

典型用法:

#include

#include

int main(void) {

srand(time(NULL)); // 设置种子为当前时间

printf("随机数:%d\n", rand());

return 0;

}

time(NULL) 返回当前的时间戳;

srand() 通常只在程序开始时调用一次;

使用相同种子,rand() 会生成相同的随机数序列。

三、生成指定范围的随机数

通用公式:

rand() % (max - min + 1) + min;

示例:生成 1 到 100 之间的随机数

#include

#include

#include

int main(void) {

srand(time(NULL)); // 初始化种子

int r = rand() % 100 + 1; // [1, 100]

printf("随机数:%d\n", r);

return 0;

}

四、生成浮点随机数

C 标准库不直接支持浮点型随机数,可以手动转化。

示例:生成 [0.0, 1.0) 之间的随机浮点数

#include

#include

#include

int main(void) {

srand(time(NULL));

float r = (float)rand() / (RAND_MAX + 1.0f);

printf("随机小数:%f\n", r);

return 0;

}

五、常见用法示例

1. 模拟掷骰子(1~6)

int dice = rand() % 6 + 1;

2. 生成 n 个 0~99 的随机数

for (int i = 0; i < n; i++) {

printf("%d ", rand() % 100);

}

3. 随机选择数组元素

char *colors[] = {"red", "green", "blue"};

int index = rand() % 3;

printf("随机颜色:%s\n", colors[index]);

六、常见误区与注意事项

误区/问题

原因说明

解决方案

每次运行结果都相同

没有调用 srand() 设置种子

添加 srand(time(NULL))

每次循环中都调用 srand

每次种子相同,导致数值相同

srand() 只需调用一次

rand() % n 非均匀分布

rand() 低位不够随机,尤其在非 2^n 的范围内

可使用更复杂的算法生成均匀分布(例如 Mersenne Twister)

七、完整练习示例:生成 10 个 1~50 的随机数

#include

#include

#include

int main(void) {

srand(time(NULL));

printf("生成 10 个 [1, 50] 的随机数:\n");

for (int i = 0; i < 10; i++) {

int r = rand() % 50 + 1;

printf("%d ", r);

}

printf("\n");

return 0;

}

小结

函数

作用

rand()

生成伪随机整数

srand()

设置随机种子

time()

获取时间戳(常用于种子)

rand() % n + x

生成指定范围内的数

rand() 生成的是伪随机数,安全性不高;

仅适用于一般用途,不建议用于加密或高强度随机性需求。

相关探索