本文实例讲述了C++常见获取随机数的方法。分享给大家供大家参考,具体如下:
方法一:
使用 rand
函数可以获取,如下。
#include<iostream>#include<ctime>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<iostream>#include<ctime>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<iostream>#include<ctime>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<iostream>#include<ctime>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<iostream>#include<ctime>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<iostream>#include<ctime>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:这里再提供几款相关工具供大家参考使用:
在线随机数生成工具:
http://tools.jb51.net/aideddesign/rnd_num
在线随机生成个人信息数据工具:
http://tools.jb51.net/aideddesign/rnd_userinfo
在线随机字符/随机密码生成工具:
http://tools.jb51.net/aideddesign/rnd_password
在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
希望本文所述对大家C++程序设计有所帮助。
您可能感兴趣的文章:
- C语言/C++中如何产生随机数
- C/C++产生指定范围和不定范围随机数的实例代码
- C++编写生成不重复的随机数代码
- C++产生随机数的实现代码
- C语言/C++如何生成随机数
- C/C++产生随机数函数简单介绍
- C++随机数生成实例讲解
- 简单谈谈关于C++中大随机数的问题
- C++ 随机数与随机种子数的实例
- C++基于随机数实现福彩双色球的方法示例