C++ 生成随机数

标签 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=(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

最佳答案

因为,在您的平台上,RAND_MAX == INT_MAX

表达式range*rand() 的值永远不能大于INT_MAX。如果数学表达式大于 INT_MAX,则整数溢出将其减少到 INT_MININT_MAX 之间的数字。将其除以 RAND_MAX 将始终产生零。

试试这个表达式:

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

关于C++ 生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9484588/

相关文章:

c++ - 在 Windows 上释放 C++ 'new' 保留的虚拟内存

c++ - C++ 中的 OpenMP 和资源管理

c++ - std::is_constructible 直接上下文和友元声明

c++ - 帮助处理类和派生类

c++ - 我们如何从结构中访问#define变量

c++ - 为什么在变量中存储右值引用会导致它悬空

c++ - findHomography()中得到的矩阵的单应分解

c++ - std::bind 于 std::array 的运算符[]

c++ - gcc -Wall 引入编译器错误

c++ - 通过引用捕获 std::exception?