How to generate random float in specific range with C++

2 Answers

0 votes
#include <iostream>
#include <iomanip>
#include <random>
 
int main() {
    std::random_device rd;
    std::default_random_engine dre(rd());
    std::uniform_real_distribution<> dist(2, 7);
 
    for (int i = 0; i < 20; i++) {
        std::cout << std::setprecision(3) << dist(dre) << "\n";
    }
}
   
   
   
   
/*
run:
   
2.17
5.74
6.2
3.35
2.99
2.36
6.64
2.5
6.17
6.95
6.82
5.64
4.16
3.22
3.29
2.68
2.18
2.38
4.82
5.24
   
*/

 



answered Jun 1, 2022 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <random>
 
int main() {
    srand(time(NULL));
    
    float min = 2.0f, max = 7.0f;
    
    for (int i = 0; i < 20; i++) {
        float f = min + static_cast<float> (rand()) / (static_cast<float> (RAND_MAX / (max - min)));
        std::cout << std::setprecision(5) << f << "\n"; 
                     
    }
}
   
   
   
   
/*
run:
   
5.4677
6.192
4.6895
3.6289
3.4514
5.6374
2.9301
3.4573
4.8145
3.7966
6.44
2.4224
5.384
4.2263
5.0997
3.0506
3.9511
3.0207
3.256
6.5089
   
*/

 



answered Jun 1, 2022 by avibootz

Related questions

3 answers 166 views
1 answer 132 views
1 answer 185 views
1 answer 142 views
1 answer 159 views
1 answer 143 views
...