C++随机数的产生

版权声明:转载记得标明作者哦 https://blog.csdn.net/KiWi_VC/article/details/80425813

C++中我们经常会用到随机数,而随机数的生成我们通常会用到rand()和srand()函数,由于rand()的内部实现是用线性同余法来做的,所以并不能生成真正的随机数,而是在一定范围内可看为随机数的伪随机数。

Rand()函数

但有rand()函数只会返回一个0到RAND_MAX之间的数字,RAND_MAX的值与int的位数有关。不过rand()是一次性的,因为系统默认的随机种子为1,如果随机种子不变的话,那么产生的随机数也会是同一个,这就需要用到我们的srand()函数了。

Srand()函数

srand()函数可以设置rand()函数产生随机数时的随机种子数,通过设置不同的种子,我们可以产生不同的随机数,一般情况下,我们通常会用系用时间作为种子,一般写作:srand((unsigned int)time(NULL)),因为这里用到了time,所以要引入<ctime>的头文件

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    srand((unsigned int)time(NULL));
    for(int i=0; i<5; i++)
    {
        cout<<rand()<<endl;
    }
    return 0;
}

下面总结几个常用的公式:

求[0,x)之间的整数:rand()%x;

求[a,b)之间的整数:rand()%(b-a) + a;

求[a,b]之间的整数:rand()%(b-a) + a + 1;

求(0,1)之间的浮点数:rand()/double(RAND_MAX);

示例:

求[0,10)之间的整数

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    int x = 10;
    srand((unsigned int)time(NULL));
    for(int i=0; i<5; i++)
    {
        cout<<rand()%x<<endl;
    }
    return 0;
}

求[5,15]之间的整数

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    int a = 5,b = 15;
    srand((unsigned int)time(NULL));
    for(int i=0; i<5; i++)
    {
        cout<<rand()%(b - a) + a + 1<<endl;
    }
    return 0;
}

求(0,1)之间的浮点数

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    srand((unsigned int)time(NULL));
    for(int i=0; i<5; i++)
    {
        cout<<rand()/double(RAND_MAX)<<endl;
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/KiWi_VC/article/details/80425813