开发者

Generate Random number between 0 and 10

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


random_integer = rand()%10; should do the trick I guess.

random_integer = rand()%11; for all numbers between 0 and 10, 10 included...


See this example of a uniform integer distribution in boost::random:

http://www.boost.org/doc/libs/1_46_1/doc/html/boost_random/tutorial.html#boost_random.tutorial.generating_integers_in_a_range

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜