How can i generate Random numbers between 0 and 10? Can I have a sample for this random number generation?
1) You shouldn't use rand()
, it has bad distribution, short period etc...
2) You shouldn't use %x
when MaxValue % x != 0
because you mess your uniform distribution (suppose you don't use rand()), e.g. 32767 % 10 = 7
so number 0-7 are more likely to get
Watch this for more info: Going native 2013 - Stephan T. Lavavej - rand() Considered Harmful
You should use something like:
#include <random>
std::random_device rdev;
std::mt19937 rgen(rdev());
std::uniform_int_distribution<int> idist(0,10); //(inclusive, inclusive)
I in my codes use something like this:
template <typename T>
T Math::randomFrom(const T min, const T max)
{
static std::random_device rdev;
static std::default_random_engine re(rdev());
typedef typename std::conditional<
std::is_floating_point<T>::value,
std::uniform_real_distribution<T>,
std::uniform_int_distribution<T>>::type dist_type;
dist_type uni(min, max);
return static_cast<T>(uni(re));
}
NOTE: the implementation is not thread safe and constructs a distribution for every call. That's inefficient. But you can modify it for your needs.
/* rand example: guess the number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand ( time(NULL) );
/* generate secret number: */
iSecret = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGuess);
if (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);
puts ("Congratulations!");
return 0;
}
iSecret variable will provide the random numbers between 1 and 10
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