1.rand()函数
获得的随机数是唯一确定的 不是变化的
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
count << rand() << endl;
return 0;
}
随机数大小是在0到rand_max,值为2147483647,它是在stdlib中实现的。如果想固定随机数的范围,通过%或/来实现。
2.srand()函数
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 1000; i++)
count << rand() << endl;
return 0;
}
在这里,我们需要引入ctime库,其中time(0)是获取从1970年开始的时间,然后再获取rand(),这时的rand就是随机变化的了。
但是这里获取的值是不确定的,而我们如果想获得某一范围内的值,也很简单。
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 100; i++)
count << rand() % 100 << endl;
return 0;
}
上述使用求余数的方法,可以获得0-100之间的值。
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 100; i++)
count << (rand() % 10)*0.1 << endl;
return 0;
}
上述可以获得0-1之间的数。
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 100; i++)
if (i % 2 == 0)
count << (rand() % 10)*0.1 << endl;
else
count << (rand() % 10)*-0.1 << endl;
return 0;
}
上述可以获得-1到1之间的数。
上述程序虽然可以得到正随机数和负随机数,但是是交替出现的,还是不够随机。所以我们可以采用下面的方式。
#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;
}