Use of rand()
We can generate random integers with the help of the rand() and srand() functions. There are some limitations to using srand() and rand(). To know more about the srand() and rand() functions refer to srand() and rand() in C++.
Approach: We can modify the approach we used to find a random integer here to find a random float,
Example:
C++
// C++ program to generate random float numbers #include <bits/stdc++.h> using namespace std; float randomFloat() { return ( float )( rand ()) / ( float )( rand ()); } signed main() { // seeds the generator srand ( time (0)); for ( int i = 0; i < 5; i++) { // generate different sequence of random float // numbers cout << randomFloat() << endl; } return 0; } |
Output
1.95347 0.329458 2.98083 0.870023 0.114373
Time Complexity: O(1)
Auxiliary Space: O(1)
Say someone wants to generate the fraction part only then,
Example:
C++
// C++ program to generate random float numbers #include <bits/stdc++.h> using namespace std; float randomFloat() { return ( float )( rand ()) / ( float )(RAND_MAX); } signed main() { // seeds the generator srand ( time (0)); for ( int i = 0; i < 5; i++) { // generate different sequence of // random float numbers cout << randomFloat() << endl; } return 0; } |
Output
0.408574 0.209153 0.189758 0.57597 0.843264
Time Complexity: O(1)
Auxiliary Space: O(1)
Generate a Random Float Number in C++
Random floating numbers can be generated using 2 methods:
- Using rand()
- Using uniform real distribution
Contact Us