Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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 141 views
1 answer 111 views
1 answer 160 views
1 answer 124 views
1 answer 145 views
1 answer 126 views
...