例如,以下表达式:
我们如何使它生成
谢谢。
r = (rand() % 10)+1;
生成一个从1-10
的随机数。我们如何使它生成
0-10
的随机数?谢谢。
你离成功就差一步了!rand()
函数返回一个相当大的范围内(0到RAND_MAX
)的随机值。使用模运算符将其限制在较小的范围内(从 0 到 9,因为模数是 10),然后再加上 1 将其转换为从 1 到 10 的范围。
要获取 0 到 10 之间的值,可以使用 rand
函数并对其值进行 11 取模:
r = rand() % 11;
更普遍地,为了在范围[0,n]内获得随机值,您可以编写以下代码
r = rand() % (n + 1);
最后,若要获取范围在 [k, n + k] 内的值,你可以写成:
r = rand() % (n + 1) + k;
当然,正如纯粹主义者所指出的那样,这并不能确保为您提供真正均匀的值,因为使用rand()
取模某个值将不能均匀分布所有整数。这通常不是一个问题(您可能只会有很小的偏差),但如果是,您可能需要考虑寻找比rand()
更强大的随机数生成器。
rand()
最严重的问题是单个随机变量的非均匀分布,以及随机变量之间的相关性。 - CodesInChaosr = rand() % 11;
在C++11中,使用std::uniform_real_distribution生成均匀分布要简单得多,而且出错概率更低。对于整数情况,可以使用std::uniform_int_distribution。下面是一个使用std::uniform_real_distribution的示例,它显示了一个简单的图形,以粗略地演示它是均匀的:
#include <iostream>
#include <iomanip>
#include <string>
#include <random>
int main()
{
std::random_device rd;
//
// Engines
//
std::mt19937 e2(rd());
//std::knuth_b e2(rd());
//std::default_random_engine e2(rd()) ;
std::uniform_real_distribution<> dist(0, 10);
const int nstars=95; // maximum number of stars to distribute
const int nintervals=10; // number of intervals
int p[nintervals]={};
for (int i=0; i<100000; ++i)
{
double number = dist(e2);
++p[int(number)];
}
std::cout << std::fixed; std::cout.precision(1);
for (int i=0; i<nintervals; ++i)
{
std::cout << float(i) << "-" << std::setw(4) << float(i+1) << ": ";
std::cout << std::string(p[i]*nstars/100000,'*') << std::endl;
}
return 0 ;
}
样例结果:
0.0- 1.0: *********
1.0- 2.0: *********
2.0- 3.0: *********
3.0- 4.0: *********
4.0- 5.0: *********
5.0- 6.0: *********
6.0- 7.0: *********
7.0- 8.0: *********
8.0- 9.0: *********
9.0-10.0: *********
有些示例代码取自于这个参考文献。
#include <iostream>
#include <random>
int main()
{
std::random_device device;
std::default_random_engine engine(device());
std::uniform_int_distribution<int> r(0, 10);
std::cout << r(engine) << std::endl;
}
(rand() % 11)
更好?除了您可以选择不同的引擎和来源之外。您应该在答案中添加更多上下文。 - HSchmaleuniform_int_distribution
对象。 - Throw Away Account#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); // Seed random number generator
unsigned int r = rand() % 10; // Generate random number
}