How can I create a pseudo-randomized integer that is constantly changing? This way, I could enter:
cout << randomInt << endl;
cout << randomInt << endl;
cout << randomInt << endl;
and the program would return something like:
45.7
564.89
1.64
(I'm not sure if any of this makes any sense.)
Create a class representing the Random number:
class Random {
};
Then overload operator<<
:
std::ostream& operator<<(std::ostream& os, const Random& random) {
return os << generate_random();
}
Use as:
int main() {
Random random;
std::cout << random;
std::cout << random;
std::cout << random;
return 0;
}
Obviously, you need to implement 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With