Make a random integer that is constantly changing?

How can I create a pseudo-randomized integer that is constantly changing? So I could enter:

cout << randomInt << endl; cout << randomInt << endl; cout << randomInt << endl; 

and the program will return something like:

 45.7 564.89 1.64 

(I'm not sure this makes sense.)

+4
source share
5 answers

Create a class representing a random number:

 class Random { }; 

Then reload 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 .

+8
source

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 rolls of bone.

If you need floating point values โ€‹โ€‹instead of integers, use std::uniform_real_distribution instead of std::uniform_int_distribution .

+5
source

This is exactly what std::rand 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 } 

Demo

+4
source

Make a class with one implicit conversion

 class t { operator int() { return 42; } }; int main() { t test; std::cout << t <<'\n'; return test; } 

and of course, any other members you want, just no other conversion operators.

+2
source

This will not play well with other random code ...

 #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"; } 

This is a pretty bad idea.

+1
source

All Articles