简体   繁体   English

生成32位随机数时出现问题

[英]problems generating 32 bit random numbers

I want to generate a random number between specified range, but when i run the following code. 我想在指定范围之间生成一个随机数,但是当我运行以下代码时。 it gives error , can any one explain the error please? 它给出错误,任何人都可以解释该错误吗?

#include <iostream>
#include <random>
using namespace std;
unsigned long int starting=2347483648;
unsigned long int ending=3994967296;
unsigned int rand(unsigned long int first,unsigned long int last)
{
    std::random_device rd; 
    std::mt19937 eng(rd()); 
    std::uniform_int_distribution<> distr(first, last); 
    return  (unsigned int)distr(eng) << ' '; 
}
int main()
{
  cout<<rand(1,ending);//generate random number in this range
}

The program breaks and gives an error 程序中断并给出错误

invalid min and max arguments for uniform_int 统一_无效的最小和最大参数

Explain the reason of error and tell me how can i generate the random numbers between the above specified range 请说明错误原因,并告诉我如何生成上述指定范围之间的随机数

Try this: 尝试这个:

    std::uniform_int_distribution<unsigned long int> distr(first, last); 
    return  (unsigned int)distr(eng); 
}

I also removed the errorneous << ' ' which is left-shifting with an space character, rather than appending a space to the output. 我还删除了错误的<< ' ' ,它左移了一个空格字符,而不是在输出后附加一个空格。

int main()
{
  cout<<rand(1,ending) << " ";
}

When ending (or last) is converted into an int, it becomes -300000000 . ending (或最后)被转换成一个int,变得-300000000 ending also becomes max() for distr, so ending == distr.max() . 对于distr, ending也变为max() ,因此ending == distr.max() Using std::numeric_limits<int>::min() , we can see that the resulting value can fit into an int. 使用std::numeric_limits<int>::min() ,我们可以看到结果值可以适合int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM