C ++创建一个介于0.1和10之间的随机小数 [英] c++ create a random decimal between 0.1 and 10
本文介绍了C ++创建一个介于0.1和10之间的随机小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么做?
这是我这样做的尝试:
srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 10 + 0.5;
在0到某个int x之间创建随机 integer 的方法又是什么. [0,x]
Also what is the way of creating a random integer between 0 and some int x. [0,x]
推荐答案
C ++ 11方式:
The C++11 way:
#include <random>
std::random_device rd;
std::default_random_engine generator(rd()); // rd() provides a random seed
std::uniform_real_distribution<double> distribution(0.1,10);
double number = distribution(generator);
如果只需要整数,请改用以下分布:
If you only want integers, use this distribution instead:
std::uniform_int_distribution<int> distribution(0, x);
在这方面,C ++ 11确实功能强大且设计合理.生成器与分发的选择是分开的,要考虑范围,线程安全,性能好,人们花费大量时间来确保它们都是正确的.最后一部分比您想象的要难解决.
C++11 is really powerful and well-designed in this respect. The generators are separate from the choice of distribution, ranges are taken into account, thread safe, performance is good, and people spent a lot of time to make sure it's all correct. That last part is harder to get right than you think.
这篇关于C ++创建一个介于0.1和10之间的随机小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文