How to generate a random float number between 0.0 and 1.1 in C++

3 Answers

0 votes
#include <iostream>
#include <random>
#include <iomanip>

int main() {
    std::random_device rd;
    std::default_random_engine eng(rd());
    std::uniform_real_distribution<float> dist(0.0, 1.1);

    for (int i = 0; i < 7; i++) {
        std::cout << std::setprecision(6) << dist(eng) << "\n";
    }
    
    return 0;
}
 
 
 
 
/*
run:
 
0.60879
0.839633
0.904362
0.919533
0.68299
0.516155
0.412744
 
*/

 



answered May 17, 2021 by avibootz
0 votes
#include <iostream>
#include <random>
#include <iomanip>

int main() {
    srand(time(NULL));

    for (int i = 0; i < 7; i++) {
        std::cout << std::setprecision(6) << 0.0 + 
                (float)(rand()) / ((float)(RAND_MAX/(1.0 - 0.0))) << "\n";
    }
    
    return 0;
}
 
 
 
 
/*
run:
 
0.508002
0.173533
0.00365777
0.668774
0.891013
0.628021
0.268846
 
*/

 



answered May 17, 2021 by avibootz
0 votes
#include <iostream>
#include <random>
#include <iomanip>
  
int main() {
    srand(static_cast <unsigned> (time(0)));
  
    for (int i = 0; i < 7; i++) {
        std::cout << std::setprecision(6) << 0.0 + 
                static_cast <float> (rand()) / static_cast <float> (RAND_MAX) << "\n";
    }
      
    return 0;
}
   
   
   
   
/*
run:
   
0.404251
0.354416
0.512682
0.499378
0.916284
0.730501
0.06082
   
*/

 



answered Jul 10, 2021 by avibootz
edited Jul 10, 2021 by avibootz

Related questions

1 answer 181 views
1 answer 192 views
1 answer 351 views
1 answer 142 views
3 answers 399 views
...