C ++生成随机数 [英] C++ generating random numbers
问题描述
我的输出是20随机1,而不是10和1之间,任何人都可以解释为什么会发生这种情况?
#include < iostream>
#include< ctime>
#include< cstdlib>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest = 1,highest = 10;
int range =(最高 - 最低)+1;
for(int index = 0; index< 20; index ++){
random_integer = lowest + int(range * rand()/(RAND_MAX + 1.0));
cout<< random_integer<< endl;
}
}
输出:
$ b $因为,在您的平台上,
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1RAND_MAX == INT_MAX
。
表达式
range * rand()
永远不能取大于INT_MAX的值
。如果数学表达式大于INT_MAX
,则整数溢出将其减小为INT_MIN
和INT_MAX
。RAND_MAX
将总会产生零。
尝试此表达式:
random_integer = lowest + int(range *(rand()/(RAND_MAX + 1.0)))
My output is 20 random 1's, not between 10 and 1, can anyone explain why this is happening?
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand((unsigned)time(0)); int random_integer; int lowest=1, highest=10; int range=(highest-lowest)+1; for(int index=0; index<20; index++){ random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0)); cout << random_integer << endl; } }
output: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
解决方案Because, on your platform,
RAND_MAX == INT_MAX
.The expression
range*rand()
can never take on a value greater thanINT_MAX
. If the mathematical expression is greater thanINT_MAX
, then integer overflow reduces it to a number betweenINT_MIN
andINT_MAX
. Dividing that byRAND_MAX
will always yield zero.Try this expression:
random_integer = lowest+int(range*(rand()/(RAND_MAX + 1.0)))
这篇关于C ++生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!