[英]c++ create a random decimal between 0.1 and 10
How would I do this? 我该怎么做?
This is my attempt of doing so: 这是我这样做的尝试:
srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 10 + 0.5;
Also what is the way of creating a random integer between 0 and some int x. 另外,在0和某些int x之间创建一个随机整数的方法是什么。 [0,x]
[0,x]中
The C++11 way: C ++ 11方式:
#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 is really powerful and well-designed in this respect. 在这方面,C ++ 11非常强大且设计精良。 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.
最后一部分比你想象的更难做到。
srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 9.9 + 0.1;
To show up to 2 decimal places: 要显示最多2个小数位:
printf("%.2lf\n", seed);
If the x
you need is smaller than RAND_MAX
, then use 如果您需要的
x
小于RAND_MAX
,则使用
seed = rand() % (x+1);
to generate an integer in [0, x]
. 在
[0, x]
生成一个整数。
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
float r(int fanwei)
{
srand( (unsigned)time(NULL) );
int nTmp = rand()%fanwei;
return (float) nTmp / 10;
}
int main(int argc, const char * argv[])
{
cout<<r(100)<<endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.