C stdlib rand() 函数
示例
显示 10 个介于 1 和 100 之间的随机数
// Initialize the randomizer using the current timestamp as a seed
// (The time() function is provided by the <time.h> header file)
srand(time(NULL));
// Generate random numbers
for (int i = 0; i < 10; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
自己动手试一试 »
定义和用法
rand()
函数返回一个非负整数。
此函数生成的数字是伪随机的,这意味着如果掌握足够的信息,就有可能预测它们。为了使数字看起来更随机,应该使用 srand()
函数,并为每次程序运行时提供一个不同的值来播种。
rand()
函数定义在 <stdlib.h>
头文件中。
语法
rand()
技术详情
返回 | 一个表示随机整数的 int 值。 |
---|