I'm using the c++ stdlib library to generate a random number with the rand() function, but every time I compile I get 41:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int a = rand();
cout<<a<<endl;
system("pause");
return 0;
}
I'm learning C++ now and I don't know what I'm doing wrong.
The mistake is that you never start the randon seed which you have to do with
After that you can call
rand()
and get different values.Try that code, it didn't compile but I'm sure it will work.
Also I think it
rand()
returns a number between 0 - 1 and this is adouble
, so you have to be careful with that.Shassain 's answer, while valid, does not mention important parts of random number generation.
The use of
std::rand
.The algorithm
std::rand
is not part of the C++ specification and therefore may not be portable with questionable results and performance, the generation algorithm may vary between implementations and leaves little or no control to the programmer. For this and other reasons , deprecation is being studied .The C++ Standard Library has offered standard pseudo-random number generation utilities since 2011. These new utilities allow the programmer to control both the generation algorithm and the distribution.
Proposal.
Taking into account the above, if you use the
<random>
C++11 header your code could look like this:The above code already generates random numbers (in the indicated range) that vary on each execution without the need to imbue a seed.