[英]c++ rand() strange behavior
I see a very strange behavior when using rand() in c++. 在C ++中使用rand()时,我看到一个非常奇怪的行为。 Here is my code.
这是我的代码。
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <limits.h>
#define N 10
int main() {
srand(time(NULL));
while(true) {
int i = N * ((double) rand() / (RAND_MAX));
//std::cout << i << std::endl; // If there is any code here, everything goes fine.
if (i == N) {
std::cout << "i " << i << " should never happen" << std::endl;
} else {
std::cout << ".";
}
}
}
Here is the output: 这是输出:
i 10 should never happen
i 10 should never happen
i 10 should never happen
...
It really doesn't make sense to me because I think i will never ever be 10. The strange thing is that it works perfectly fine if I try any of the following: 这对我来说真的没有任何意义,因为我认为我永远不会10岁。奇怪的是,如果我尝试以下任何一种方法,它都可以正常工作:
My compiler is mingw32-g++.exe (TDM-2 mingw32) 4.4.1. 我的编译器是mingw32-g ++。exe(TDM-2 mingw32)4.4.1。
This really confuses me, could anyone tell me what's going on? 这真的让我感到困惑,有人可以告诉我发生了什么吗?
This is to be expected: 这是可以预期的:
The
rand()
function returns a pseudo-random integer in the range 0 toRAND_MAX
inclusive (ie, the mathematical range [0,RAND_MAX
]).rand()
函数返回一个伪随机整数,范围为0到RAND_MAX
(含)(即数学范围[0,RAND_MAX
])。— man rand(3)
— 兰德(3)
So rand() / RAND_MAX
can be 1 because the range is inclusive. 因此
rand() / RAND_MAX
可以为1,因为范围是包含在内的。 Your fix with RAND_MAX + 1
is usually the option that is taken. 通常使用
RAND_MAX + 1
修复。
That being said, there are better options to generate random numbers in a range that will yield a uniform distribution. 话虽这么说,还有更好的选择来生成在一定范围内会产生均匀分布的随机数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.