2475 views|0 replies

3836

Posts

19

Resources
The OP
 

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):

This post is from Microcontroller MCU
 

Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list