如何在C++的-10到10区间内制作随机数?
srand(int(time(0)));//seed
for(int i = 0; i < size; i++){
myArray[i] = 1 + rand() % 20 - 10;//this will give from -9 to 10
myArray2[i] =rand() % 20 - 10;//and this will -10 to 9
}
Run Code Online (Sandbox Code Playgroud)
zol*_*i2k 10
为了得到均匀分布,你必须划分RAND_MAX第一
static_cast<int>(21*static_cast<double>(rand())/(RAND_MAX+1)) - 10
Run Code Online (Sandbox Code Playgroud)
运用
rand() % 21 - 10;
Run Code Online (Sandbox Code Playgroud)
更快,常用于应用程序,但结果分布不均匀.功能rand()从生成的数字0来RAND_MAX.如果RAND_MAX%21!=0以较高的概率生成较小的数字.
您也可以考虑使用模数方法,但删除一些随机数:
int randMax = RAND_MAX - RAND_MAX%21;
int p=RAND_MAX+1;
while(p>randMax)
p=rand();
x=p%21 - 10;
Run Code Online (Sandbox Code Playgroud)
编辑(约翰内斯和史蒂夫的评论):
当划分时,RAND_MAX范围中会有一些数字会被更频繁地选取,因此正确的处理方法是拒绝会导致目标间隔分布不均匀的数字.
使用Boost Random Library(Danvil提到),消除了随机数均匀性的所有问题.
你需要21的范围,而不是20,所以做这样的事情:
x = rand() % 21 - 10;
Run Code Online (Sandbox Code Playgroud)
使用Boost随机数库.内置随机数发生器的分配质量差.此外,boost为您提供了许多有用的生成器.
// based on boost random_demo.cpp profane demo
#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
int main() {
boost::mt19937 gen(42u); // seed generator
boost::uniform_int<> uni_dist(-10, 10); // random int from -10 to 10 inclusive
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
uni(gen, uni_dist); // callable
for(int i = 0; i < 10; i++)
std::cout << uni() << ' ';
}
Run Code Online (Sandbox Code Playgroud)
输出:
-3 6 9 -7 5 6 2 2 -7 -1
Run Code Online (Sandbox Code Playgroud)
未来的注意事项:现在已经在C++ 11中内置了.