+ 2

How can I generate random numbers between a negative and positive value?

I've tried with -MIN+rand() %(-MIN+MAX+1) and other combinations but I'm stuck.

10th Feb 2018, 5:31 PM
Javier Alonso Delgado
Javier Alonso Delgado - avatar
5 Answers
+ 3
The algorithm goes like this min + rand() % ( max - min + 1 ) works with negatives and positives.
10th Feb 2018, 5:57 PM
Dennis
Dennis - avatar
+ 6
rand(10) - 5 will generate numbers between -5 and +5
10th Feb 2018, 5:39 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 2
C++11 was 7 years ago. Can we please stop using rand()? <random> is much better. #include <iostream> #include <random> int main() { /* your desired int type*/ min; std::cin >> min; /* your desired int type*/ max; std::cin >> max; std::random_device truly_random_seed; std::default_random_engine dank_engine(truly_random_seed()); std::uniform_int_distribution</* your desired int type*/> distribution(min, max); /* your desired int type*/ random_number = distribution(dank_engine); std::cout << random_number << std::endl; return 0; }
10th Feb 2018, 9:06 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
(rand()%range)±shift
10th Feb 2018, 5:48 PM
Alex
Alex - avatar