【c++】生成浮點隨機數


 

c++11:std::uniform_real_distribution<>直接求(尖括號不填默認生成double)

隨機10個在1-2之間的浮點數

#include <random>
#include <iostream>
 
int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_real_distribution<> dis(1.0, 2.0);
    for (int n = 0; n < 10; ++n) {
        // Use dis to transform the random unsigned int generated by gen into a 
        // double in [1, 2). Each call to dis(gen) generates a new random double
        std::cout << dis(gen) << ' ';
    }
    std::cout << '\n';
}

結果:

1.80829 1.15391 1.18483 1.38969 1.36094 1.0648 1.97798 1.27984 1.68261 1.57326

https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution

 

 

c++11 之前:通過std::rand()和RAND_MAX間接求

如果要實現0-1之間隨機浮點數的函數,可以如下: 

double randf() { 
     return (double)(rand()/(double)RAND_MAX); 
} 

https://blog.csdn.net/enterlly/article/details/54310945

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM