C ++生成随机数 [英] C++ generating random numbers

查看:111
本文介绍了C ++生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输出是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;
}
}




输出:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

$ b $因为,在您的平台上, RAND_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 than INT_MAX. If the mathematical expression is greater than INT_MAX, then integer overflow reduces it to a number between INT_MIN and INT_MAX. Dividing that by RAND_MAX will always yield zero.

Try this expression:

random_integer = lowest+int(range*(rand()/(RAND_MAX + 1.0)))

这篇关于C ++生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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