如何创建一个不断变化的伪随机整数?这样,我可以输入:
cout << randomInt << endl;
cout << randomInt << endl;
cout << randomInt << endl;
并且程序将返回如下内容:
45.7
564.89
1.64
(我不确定这是否有任何意义。)
创建一个表示随机数的类:
class Random {
};
然后重载operator<<
:
std::ostream& operator<<(std::ostream& os, const Random& random) {
return os << generate_random();
}
用于:
int main() {
Random random;
std::cout << random;
std::cout << random;
std::cout << random;
return 0;
}
显然,您需要实现generate_random
.
Using the new C++11 pseudo-random number generation classes:
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for(int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
The above simulates ten dice rolls.
If you want floating-point values instead of integers, use std::uniform_real_distribution
instead of std::uniform_int_distribution
.
This is exactly what std::rand
is for:
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
{
std::srand(static_cast<unsigned>(std::time(0))); // seed
for (int i = 5; i--;) std::cout << std::rand() % 5 << '\n';
// Output are random integers
}
使用单个隐式转换创建一个类
class t { operator int() { return 42; } };
int main()
{
t test; std::cout << t <<'\n';
return test;
}
当然,无论您想要什么其他成员,都没有其他转换运算符。
这与其他随机代码不能很好地配合......
#include <ctime>
#include <cstdlib>
struct RandomInt {
RandomInt() {
static bool initialized = (srand(std::time(0)), true);
}
operator int() {
return std::rand();
}
};
#include <iostream>
std::ostream& operator<<( std::ostream& stream, RandomInt x ) {
return stream << static_cast<int>(x);
}
int main() {
RandomInt randomInt;
std::cout << randomInt << "\n";
std::cout << randomInt << "\n";
std::cout << randomInt << "\n";
}
这几乎是个坏主意。