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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7887941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:38:55  来源:igfitidea点击:

random number from -9 to 9 in C++

c++randomnumbers

提问by Danny

just wondering, if I have the following code:

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

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

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

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

回答by NPE

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

不,不会。您正在寻找:

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

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

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

回答by Davide Aversa

Your code returns number between (0-9 and 17-9) = (-9 and 8).

您的代码返回 (0-9 和 17-9) = (-9 和 8) 之间的数字。

For your information

供您参考

 rand() % N;

returns number between 0 and N-1 :)

返回 0 到 N-1 之间的数字:)

The right code is

正确的代码是

rand() % 19 + (-9);

回答by KillianDS

Do not forget the new C++11 pseudo-random functionality, could be an option if your compiler already supports it.

不要忘记新的C++11 伪随机功能,如果您的编译器已经支持它,它可能是一个选项。

Pseudo-code:

伪代码:

std::mt19937 gen(someSeed);
std::uniform_int_distribution<int> dis(-9, 9);
int myNumber = dis(gen)

回答by nurettin

You are right in that there are 18 counting numbers between -9 and 9 (inclusive).

你是对的,在 -9 和 9(含)之间有 18 个计数数字。

But the computer uses integers (the Z set) which includes zero, which makes it 19 numbers.

但是计算机使用包括零的整数(Z 集),这使它成为 19 个数字。

Minimum ratio you get from rand() over RAND_MAX is 0, so you need to subtract 9 to get to -9.

您从 rand() 获得的最小比率与 RAND_MAX 为 0,因此您需要减去 9 才能得到 -9。

The information below is deprecated. It is not in manpages aymore. I also recommend using modernC++for this task.

以下信息已弃用。它不在联机帮助页中。我还建议使用现代C++来完成这项任务。

Also, manpage for the rand functionquotes:

此外,rand 函数引用的联机帮助页

"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

and never by anything resembling

j = 1 + (rand() % 10);

(which uses lower-order bits)."

“如果你想生成一个 1 到 10 之间的随机整数,你应该总是使用高位来做,如

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

从来没有类似的东西

j = 1 + (rand() % 10);

(使用低位)。”

So in your case this would be:

所以在你的情况下,这将是:

int n= -9+ int((2* 9+ 1)* 1.* rand()/ (RAND_MAX+ 1.));

回答by Petruza

Anytime you have doubts, you can run a loop that gets 100 million random numbers with your original algorithm, get the lowest and highest values and see what happens.

任何时候你有疑问,你都可以运行一个循环,用你的原始算法得到 1 亿个随机数,得到最低和最高值,看看会发生什么。