-6

I have seen the use of math.random() in JavaScript to pick a random number between 0 and 1. Is this function also available in C++, or it is only included in Java and newer languages?

nbro
  • 15,395
  • 32
  • 113
  • 196
Varun Moghe
  • 74
  • 2
  • 3
  • 12

4 Answers4

1

There's the rand() function from <cstdlib> library, which returns a number between 0 and RAND_MAX. If you want a number between 0 and 1, you have to do a workaround with casts and divisions:

double X = ((double)rand() / (double)RAND_MAX);

This is a practical example, putting the previous code inside a function:

#include <cstdlib> //  srand, rand
#include <ctime> // time
#include <iostream> //std::cout

double random01()
{
     return ((double)rand() / (double)RAND_MAX);
}

int main()
{

    srand(time(0)); // Remember to generate a seed for srand

    for(int i=0; i< 100; ++i)
    {
        std::cout << random01()  << '\n';
    }

    return 0;
}
nbro
  • 15,395
  • 32
  • 113
  • 196
1

To use the random number generator function in C++, you need to include the header.

#include<iostream>
#include<cstdlib>

using namespace std;

int main()
{

    int randomInteger = rand();
    cout << randomInteger << endl;


}

If you want to produce numbers in a specific range, you can use the modulo operator. It's not the best way to generate a range but it's the simplest. If we use rand() % n we generate a number from 0 to n-1. By adding an offset to the result we can produce a range that is not zero based. The following code will produce 20 random numbers from 1 to 10:

#include <cstdlib> 
#include <iostream>

using namespace std;

int main() 
{ 
    int random_integer; 
    for(int index=0; index<20; index++){ 
    random_integer = (rand()%10)+1; 
    cout << random_integer << endl; 
} 
Moiz Sajid
  • 644
  • 1
  • 10
  • 20
0

Yes, the C++ library has a substantial numerics library, described in section 26 of the C++11. Specifically, the random number generation classes are described in section 26.5.

Since your question was only whether this functionality is "available in C++", the answer would be "yes".

You should be able to find plenty of examples of using the std::random_device class, and other classes from the random number generation library, by searching the Intertubes.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0
int randomNumber = rand()%100; // for 0 to 99
Evan Carslake
  • 2,267
  • 15
  • 38
  • 56