【c++】生成浮点随机数
2019-01-26 16:54 ZealouSnesS 阅读(8537) 评论(0) 编辑 收藏 举报
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