如何生成0到10之间的随机数?你能给我一个生成随机数的示例吗?
如何生成0到10之间的随机数?你能给我一个生成随机数的示例吗?
1) 不应该使用 rand()
,因为它分布不均匀,周期短等问题...
2) 当 MaxValue % x != 0
时,不应该使用 %x
,因为这会破坏你的均匀分布(假设你没有使用 rand()),例如 32767 % 10 = 7
,所以数字0-7更有可能出现。
请查看此链接了解更多信息:Going native 2013 - Stephan T. Lavavej - rand() Considered Harmful
你应该使用类似以下代码:
#include <random>
std::random_device rdev;
std::mt19937 rgen(rdev());
std::uniform_int_distribution<int> idist(0,10); //(inclusive, inclusive)
在我的代码中,我使用类似以下的语句:
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));
}
注意:该实现不是线程安全的,并且每次调用都会构造一个分布。这是低效的。但是您可以根据自己的需求进行修改。
/* 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变量将提供1到10之间的随机数。
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
random_integer = rand()%10;
应该可以解决问题。
random_integer = rand()%11;
用于生成0到10之间的所有数字,包括10在内...