如何在C中给定范围内生成随机数
例子:
Input : Lower = 50,
Upper = 100,
Count of random Number = 5
Output : 91 34 21 88 29
Explanation: lower is the lower limit of the
range and upper is the upper limit of the range.
Output contains 5 random numbers in given range.
因为C没有内置函数来生成该范围内的数字,但是C具有rand函数,该函数生成从0到RAND_MAX的随机数。借助rand(),可以生成范围内的一个数字,即num =(rand()%(上–下+ 1))+下
// C program for generating a
// random number in a given range.
#include
#include
#include
// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper,
int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() %
(upper - lower + 1)) + lower;
printf("%d ", num);
}
}
// Driver code
int main()
{
int lower = 5, upper = 7, count = 1;
// Use current time as
// seed for random generator
srand(time(0));
printRandoms(lower, upper, count);
return 0;
}
输出:
7
注意:每次运行生成的输出可能会有所不同,因为数字是随机生成的。
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。