本文实例讲述了C++常见获取随机数的方法。分享给大家供大家参考,具体如下:
方法一:
使用 rand 函数可以获取,如下。
#include
#include
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
cout << rand() << endl;
return 0;
}
随机数大小是在0到RAND_MAX,值为2147483647,它是在stdlib中定义的,如果我们希望在某个范围内,可以使用 % 结合 / 来实现。
但是不难发现,这里获得的随机数是唯一确定的,而不是变化的。所以,如果我们希望获得变化的随机数,可以使用下面的方法。
方法二:
既然使用rand函数无法获取到变化的随机数,这里就可以使用srand来实现了。
#include
#include
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 1000; i++)
cout << rand() << endl;
return 0;
}
这里,我们需要引入ctime库,其中time(0)是获取从1970年开始的时间(单位:s),然后再获取rand(),这时的rand就是随机变化得了。 如下:
但这里获取的值是不确定的,而如果我们希望获得在某一范围内的值呢,也很简单,如下所示:
#include
#include
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 100; i++)
cout << rand() % 100 << endl;
return 0;
}
如上,使用求余数的方法,我们可以获得0 - 100之间的值。
而如果我们希望得到0 - 1之间的数呢? 如下所示:
#include
#include
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 100; i++)
cout << (rand() % 10) * 0.1 << endl;
return 0;
}
而我们希望得到-1 到 1 之间的数呢?
#include
#include
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 100; i++)
if (i % 2 == 0)
cout << (rand() % 10) * 0.1 << endl;
else
cout << (rand() % 10) * -0.1 << endl;
return 0;
}
上面的程序虽然可以得到正随机数和负随机数,但是是交替出现的,还是不够随机,所以我们可以采用下面的方式:
#include
#include
using namespace std;
int main()
{
srand(time(0));
double a;
for (int i = 0; i < 100; i++)
if (rand() % 10 > 0.4)
{
cout << (rand() % 10) * 0.1 << endl;
}
else
{
a = (rand() % 10) * -0.1;
if (a == -0.0)
{
cout << 0 << endl;
}
else
{
cout << a << endl;
}
}
return 0;
}
这样,我们就可以得到真正的随机数了,后面使用 a == -0.0 判断是为了防止输出 -0 的情况。 最终结果如下:
PS:这里再提供几款相关工具供大家参考使用:
希望本文所述对大家C++程序设计有所帮助。