C 随机数
随机数
在 C 语言中,你可以使用 rand() 函数生成随机数,该函数位于 <stdlib.h> 库中。
默认情况下,每次运行程序时,rand() 都会生成相同的数字序列。
为了在每次运行中获得不同的结果,您还可以使用 srand() 设置一个"起点"(称为 种子)。
既然你刚刚学习了日期和时间,现在你可以使用当前时间作为种子(因为它总是在变化)。
为此,您需要在程序中包含 <time.h>。
基本随机数
函数 rand() 返回一个随机整数。
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int r = rand();
printf("%d
", r);
return 0;
}
注意: 如果您多次运行此程序,每次都会看到相同的数字。这是因为我们尚未设置种子。
设置随机数生成器种子
要使程序每次运行都得到不同的数字,必须给 rand() 一个 起始点(种子)。
你可以使用srand()来完成此操作。一个常见的技巧是使用当前时间作为种子,因为时间总是在变化的:
示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // seed with current time
printf("%d
", rand());
printf("%d
", rand());
printf("%d
", rand());
return 0;
}
提示: 只需在 main 函数开始时调用一次 srand() 函数。不要在循环中再次调用它。
生成指定范围内的随机数
通常您需要生成较小范围内的数字,例如 0 到 9。您可以使用取模运算符 %:
示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int x = rand() % 10; // 0..9
printf("%d
", x);
return 0;
}
现实生活中的例子:掷骰子
随机数在现实生活中的一个常见应用是掷六面骰子。我们可以通过使用rand() % 6函数来模拟这个过程,生成0到5之间的数字,然后加1得到1到6之间的数字范围:
示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int dice1 = (rand() % 6) + 1;
int dice2 = (rand() % 6) + 1;
printf("You rolled %d and %d (total = %d)", dice1, dice2, dice1 + dice2);
return 0;
}
每次运行程序时,都会生成两个介于 1 到 6 之间的随机数,就像现实生活中掷两个骰子一样。

