+ 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.
5 Respostas
+ 3
The algorithm goes like this
min + rand() % ( max - min + 1 )
works with negatives and positives.
+ 6
rand(10) - 5 will generate numbers between -5 and +5
+ 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;
}
+ 1
(rand()%range)±shift