C 语言 - 随机数
随机数
在 C 语言中,您可以使用 rand() 函数生成随机数,该函数位于 <stdlib.h> 库中。
默认情况下,每次运行程序时,rand() 都会给出相同的数字序列。为了在每次运行时获得不同的结果,您还可以使用 srand() 来设置一个"起始点"(称为种子)。既然您刚刚学习了日期和时间,现在可以使用当前时间作为种子(因为它总是在变化)。为此,您需要在程序中包含 <time.h>。
基本随机数
rand() 函数返回一个随机整数。
实例
#include <stdio.h>
#include <stdlib.h>
int main() {
int r = rand();
printf("%d\n", r);
return 0;
}
注意:如果您多次运行此程序,每次都会看到相同的数字。这是因为我们还没有设置种子。
为随机数生成器设置种子
为了在每次运行程序时获得不同的数字,您必须给 rand() 一个起始点(种子)。
您可以使用 srand() 来做到这一点。一个常用的技巧是使用当前时间作为种子,因为时间总是在变化:
实例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // 使用当前时间作为种子
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", 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\n", 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)\n", dice1, dice2, dice1 + dice2);
return 0;
}
每次运行程序时,您将获得两个介于 1 和 6 之间的随机数,就像在现实生活中掷两个骰子一样。