生成C范围内的随机数
在这里,我们将看到如何使用C生成给定范围内的随机数。要解决此问题,我们将使用该srand()函数。当前时间将用于设定srad()方法。
此函数不能生成任何范围内的随机数,它可以生成介于0到某个值之间的数字。因此,为此,我们必须遵循一个技巧。我们将生成介于0到(上–下+1)之间的随机数,然后加上偏移的下限。
示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random(int l, int r, int count) { //this will generate random number in range l and r
int i;
for (i = 0; i < count; i++) {
int rand_num = (rand() % (r - l + 1)) + l;
printf("%d ", rand_num);
}
}
main() {
int lower = 10, upper = 15, count = 15;
srand(time(0)); //current time as seed of random number generator
generate_random(lower, upper, count);
printf("\n");
}输出结果
15 11 13 10 13 10 15 11 14 12 12 13 12 13 14
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短