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?
-
It does not really make sense to compare languages like this, in C++ you have a few choices as my [answer here lists](http://stackoverflow.com/a/19553318/1708801) basically `random header`, `boost` and `rand()` – Shafik Yaghmour Dec 16 '14 at 02:54
-
I have not coded in C++ in ages. Isn't it rand? – epascarello Dec 16 '14 at 02:54
-
The C++ standard library have many [functions and classes for pseudo-random number generation](http://en.cppreference.com/w/cpp/numeric/random). – Some programmer dude Dec 16 '14 at 02:55
-
I know about the rand but what i am asking i sdoes math.random(); works in c++ or not. – Varun Moghe Dec 16 '14 at 03:00
-
Did you try? You would know the answer. – epascarello Dec 16 '14 at 03:02
-
Java is not Javascript, in case your formulation implied that they were similar or related languages (which they aren't) – Jivan Dec 16 '14 at 03:29
4 Answers
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;
}

- 15,395
- 32
- 113
- 196
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;
}

- 644
- 1
- 10
- 20
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.

- 114,536
- 5
- 94
- 148