如何使用rand函数生成特定范围内的数字? [英] How to use the rand function to make numbers in a specific range?
本文介绍了如何使用rand函数生成特定范围内的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在特定范围内生成随机数,例如在 18 到 35 之间选择一个随机数"?我怎样才能用 rand()
函数做到这一点?
I would like to make random numbers in a specific range, like "pick a random number between 18 and 35"? How can I do that with the rand()
function?
推荐答案
如果这是用 C 编写的,那么您就非常接近了.编译此代码:
If this is written in C, then you are pretty close. Compiling this code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
for (i = 0; i < 1000000; i++) {
printf("%d
", rand()%(35-18+1)+18);
}
}
并在管道中运行它会产生以下输出:
And running it in a pipeline produces this output:
chris@zack:~$ gcc -o test test.c
chris@zack:~$ ./test | sort | uniq -c
55470 18
55334 19
55663 20
55463 21
55818 22
55564 23
55322 24
55886 25
55947 26
55554 27
55342 28
55526 29
55719 30
55435 31
55669 32
55818 33
55205 34
55265 35
关键是你忘了加 1 -- 围栏错误.
The key is you forgot to add 1 -- the fencepost error.
您可以将其概括为一个函数:
You can generalize this into a function:
int random_between(int min, int max) {
return rand() % (max - min + 1) + min;
}
这篇关于如何使用rand函数生成特定范围内的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文