C++ 创建一个介于 0.1 和 10 之间的随机小数

c++ create a random decimal between 0.1 and 10

本文关键字:之间 小数 随机 创建 一个 C++      更新时间:2023-10-16

我该怎么做?

这是我这样做的尝试:

srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 10 + 0.5;

另外,在 0 和一些 int x 之间创建一个随机整数的方法是什么。 [0,x]

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);

如果您只需要整数,请改用此分布:

std::uniform_int_distribution<int> distribution(0, x);

C++11在这方面非常强大且设计精良。生成器与分布的选择是分开的,范围被考虑在内,线程安全,性能良好,人们花费大量时间来确保它都是正确的。最后一部分比你想象的更难做对。

srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 9.9 + 0.1;

要显示最多 2 位小数:

printf("%.2lfn", seed);

如果所需的x小于 RAND_MAX ,请使用

seed = rand() % (x+1);

[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;
}