生成0到10之间的随机数

kar*_*hik 2 c++ random math

如何生成0到10之间的随机数?我可以为这个随机数生成一个样本吗?

rel*_*xxx 10

1)你不应该使用rand(),它有不良分布,短期等...

2)你不应该使用%x何时MaxValue % x != 0因为你弄乱你的统一分布(假设你不使用rand()),例如32767 % 10 = 70-7号码更容易得到

观看此以获取更多信息:2013年的土生土长 - Stephan T. Lavavej - rand()被认为是有害的

你应该使用类似的东西:

#include <random>

std::random_device rdev;
std::mt19937 rgen(rdev());
std::uniform_int_distribution<int> idist(0,10); //(inclusive, inclusive) 
Run Code Online (Sandbox Code Playgroud)

我在我的代码中使用这样的东西:

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));
}
Run Code Online (Sandbox Code Playgroud)

注意:实现不是线程安全的,并为每个调用构建一个分发.那效率很低.但您可以根据需要进行修改.


kar*_*hik 6

  /* 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;
    }
Run Code Online (Sandbox Code Playgroud)

iSecret变量将提供1到10之间的随机数