Ahmed
Ahmed

Reputation: 2266

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

Upvotes: 0

Views: 1185

Answers (1)

user1508519
user1508519

Reputation:

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 also becomes max() for distr, so ending == distr.max(). Using std::numeric_limits<int>::min(), we can see that the resulting value can fit into an int.

Upvotes: 3

Related Questions