C++ Generate a random number between 0 and 1
[Copy link]
The function used to generate random numbers in C++ is rand(), and its return value is an integer.
To generate a floating point number between 0 and 1, it must be converted.
Idea: Generate a random number from 0 to N, and then divide it by N+1 to get a floating-point random number.
N can determine the precision of the result. For example, if 2 decimal places are needed, then N=99, and if 3 decimal places are needed, then N=999.
The code is as follows:
#include "stdafx.h"
#include "iostream"
#include "ctime"
#include "cstdlib"
using namespace std;
#define N 999 //The precision is 3 decimal places
int main()
{
float num;
int i;
float random[10];
srand(time(NULL));//Set the random number seed to make the random sequence generated each time different
for (int i = 0; i < 10; i++)
{
random[i] = rand() % (N + 1) / (float)(N + 1);
}
for (int i = 0; i < 10; i++)
{
cout << random[i] << endl; //Output the 10 random numbers generated
}
return 0;
}
Running result (N=999):
Running results (N=99):
|