C++ 创建一个介于 0.1 和 10 之间的随机小数
c++ create a random decimal between 0.1 and 10
我该怎么做?
这是我这样做的尝试:
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;
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- C++将浮点指针值舍入为小数位数
- 从给定的 I 和 D 序列中形成最小数
- 在cuda线程之间共享大量常量数据
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C++ 创建一个介于 0.1 和 10 之间的随机小数