Cody Gray already says what you are doing wrong here, but here is an example of this with the <random> library:
#include <random> std::mt19937 make_seeded_engine() { std::random_device r; std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; return std::mt19937(seed); } class foo { std::mt19937 engine; public: foo() : engine(make_seeded_engine()) {} int randomNum10to50(){ return std::uniform_int_distribution<>(10,50)(engine); } }; foo create; for (int i=0; i<20;i++){ cout << create.randomNum10to50() << '\n'; }
Note that rand()%50 + 10 produces numbers in the range of 10 to 59, not 10 to 50. uniform_int_distribution is better because the range you give it is the range you get, so you are unlikely spoil it. In addition, using uniform_int_distribution gives unbiased results, while rand()%50+10 has a slight deviation.
If you have a compiler with support for more than C ++ 11, you can do:
class foo{ std::mt19937 engine = make_seeded_engine(); public: int randomNum10to50(){ return std::uniform_int_distribution<>(10,50)(engine); } };
bames53
source share