我如何获得随机值在c++ 11
How do i get random value in c++ 11
我的代码:
#include <iostream>
#include <random>
void main()
{
std::random_device rd;
std::cout << "Random value: " << rd() << std::endl;
system("pause");
}
如何获得结果rd()
,并将其转换为std::string
?
既然您正在询问如何将std::random_device
的结果转换为字符串,而std::random_device
返回unsigned int
。 c++ 11提供std::to_string
,可用于将数字转换为字符串。看到这里。
#include <iostream>
#include <random>
#include <string>
int main()
{
std::random_device rd;
std::string str = std::to_string(rd());
std::cout << str << std::endl;
return 0;
}
下面是我在http://en.academic.ru/dic.nsf/enwiki/11574016上找到的一个例子
#include <random>
#include <functional>
std::uniform_int_distribution<int> distribution(0, 99);
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
int random = generator(); // Generate a uniform integral variate between 0 and 99.
int random2 = distribution(engine); // Generate another sample directly using the distribution and the engine objects.
我以前没有使用过它,但这可能会帮助你开始。
std::stringstream
是将数字转换为字符串的一种方法,下面的代码显示了各种可能的引擎和分布。对于引擎和normal distribution
,默认为Mersenne Twister
。对于可用的选项,这是一个很好的参考:
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <sstream>
int main()
{
std::random_device rd;
//
// Engines
//
std::mt19937 e2(rd());
//std::knuth_b e2(rd());
//std::default_random_engine e2(rd()) ;
//
// Distribtuions
//
std::normal_distribution<> dist(2, 2);
//std::student_t_distribution<> dist(5);
//std::poisson_distribution<> dist(2);
//std::extreme_value_distribution<> dist(0,2);
std::stringstream s1 ;
s1 << dist(e2) ;
std::string str1 = s1.str();
std::cout << str1 << std::endl ;
}
另一种转换为string
的方法是使用std::to_string
:
str1 = std::to_string( dist(e2) ) ;
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
unsigned int maxValue = 50;
std::cout << "Random value: " << rand()%maxValue; //random between 0-50
return 0;
}
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将字符随机转换为大写的函数
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 如何使用要传递给 mt19937 的可选随机种子参数设计函数
- 在C++中随机生成 20 个非重复数字
- GCC:随机构建导致执行期间分段错误
- 如何使用 SML 随机生成八进制元组
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 将正态随机变量与任意 RHO(corrcoef) 相关联