C ++中从-9到9的随机数

2022-01-17 00:00:00 random numbers c++

只是想知道,如果我有以下代码:

just wondering, if I have the following code:

int randomNum = rand() % 18 + (-9);

这会创建一个从 -9 到 9 的随机数吗?

will this create a random number from -9 to 9?

推荐答案

不,不会的.您正在寻找:

No, it won't. You're looking for:

int randomNum = rand() % 19 + (-9);

-9 和 +9 之间有 19 个不同的整数(包括两者),但 rand() % 18 只给出了 18 种可能性.这就是为什么你需要使用 rand() % 19.

There are 19 distinct integers between -9 and +9 (including both), but rand() % 18 only gives 18 possibilities. This is why you need to use rand() % 19.

相关文章