如何从 rand() 获取特定范围的数字? [英] How do I get a specific range of numbers from rand()?

查看:21
本文介绍了如何从 rand() 获取特定范围的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

srand(time(null));

printf("%d", rand());

给出一个高范围的随机数(0-32000ish),但我只需要大约 0-63 或 0-127,虽然我不知道如何去做.有什么帮助吗?

Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?

推荐答案

rand() % (max_number + 1 - minimum_number) + minimum_number

所以,对于 0-65:

So, for 0-65:

rand() % (65 + 1 - 0) + 0

(很明显,您可以将 0 去掉,但它是为了完整性).

(obviously you can leave the 0 off, but it's there for completeness).

请注意,这会略微偏向随机性,但如果您不是在做一些特别敏感的事情,则可能无需担心.

Note that this will bias the randomness slightly, but probably not anything to be concerned about if you're not doing something particularly sensitive.

这篇关于如何从 rand() 获取特定范围的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆