How to generate numbers in range [-1, 1] in c++

I have to generate numbers in range [-1, 1] in c++. How can I do this with rand if there is only positive numbers available?

1 answer

  • answered 2021-09-27 16:45 Md. Faisal Habib

    You can use rand() function.

    min_number_in_range + ( std::rand() % ( max_number_in_range - min_number_in_range + 1 ) )
    

    Another approach:

    #include <iostream>
    #include <random>
    using namespace std;
    int main()
    {
        random_device rd; // obtain a random number from hardware
        mt19937 gen(rd()); // seed the generator
        uniform_int_distribution<> distr(-1, 1); // define the range
    
        cout << distr(gen) << endl; // generate numbers
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum