0

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

5
  • If I'm not wrong, the default template argument for uniform_int_distribution is an int. And an unsigned long int cannot fit into an int. Commented Jan 13, 2014 at 17:44
  • well if the above function is called with these values rand(starting,ending), it works fine... Commented Jan 13, 2014 at 17:47
  • 1
    I gotta say, the tone of the question is not so nice.. Commented Jan 13, 2014 at 17:59
  • i didn't understand @fleetC0m ...... i didn't mean anything like that...just here for learning Commented Jan 13, 2014 at 18:01
  • I don't see why the downvotes. This problem could trip anybody up if they weren't familiar with uniform_int_distribution. Commented Jan 13, 2014 at 18:02

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it works but can you explain why the above code gives error if first argument is 1 and runs if it is "starting"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.