今天,我们就来聊一聊rand函数吧o(* ̄︶ ̄*)o~
首先,我们要了解rand函数是什么:是随机生成数函数。通过rand函数,我们可以随机生成数据,既方便出题,也方便验证题目中的极端数据。
接下来,我们可以看一下是如何使用rand函数的:
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout<<rand();//随机生成数据
return 0;
}
这个简短的代码就可以直接随机生成一个较小的(几万左右)的数据。
如果想让生成的数据不重复,我们可以这样:
/*CN*/
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
srand((int) time(NULL));
cout<<rand();
return 0;
}
在前面加一句 srand((int) time(NULL)); 就可以了。
如果想要生成大数据怎么办呢?可以自定义一个myrand()函数,就像这样:
int myrand()//随机生成大数据
{
return ((rand()<<15)^rand());
}
如果需要输出,直接cout<<myrand(); 即可。这样通过位运算,让返回的数据大小可以更大一些。
以上就是我对rand()函数的简单介绍,┏(^0^)┛
蒟蒻一枚,创作不易,不喜勿喷~!