需要的头文件
#include<iostream>//提供输入输出cout cin #include<cstdlib>//提供rand()、srand()随机函数 #include<ctime>//提供time()时间函数,用来做随机种子 using namespace std; //#include<bits/stdc++.h>//或者用万能头文件
需要的开头
srand((unsigned)time(NULL));//设置随机种子:用系统当前时间当种子,放在main函数开头
生成随机数(生成a-b任意区间的随机整数公式 rand()%(b-a+1)+a)
rand()自带的范围0-32767
#include<iostream>//提供输入输出cout cin #include<cstdlib>//提供rand()、srand()随机函数 #include<ctime>//提供time()时间函数,用来做随机种子 using namespace std; int main(){ srand((unsigned)time(NULL));//设置随机种子:用系统当前时间当种子,如果不写会随机生成同一个数,放在main函数开头 int num=rand();//调用rand()生成一个0-32767的随机数 cout<<num;//输出随机数 return 0; }
生成1-n范围内的随机数
//#include<iostream>//提供输入输出cout cin //#include<cstdlib>//提供rand()、srand()随机函数 //#include<ctime>//提供time()时间函数,用来做随机种子 #include<bits/stdc++.h> using namespace std; int main(){ srand((unsigned)time(NULL));//设置随机种子:用系统当前时间当种子,如果不写会随机生成同一个数,放在main函数开头 int n;//定义输出随机数的最大范围 cin>>n; //生成a-b任意区间的随机整数公式 rand()%(b-a+1)+a int num=rand()%n+1;//rand()%n得到0 1 .... n-3 n-2 n-1 ,+1后变成1 2 3 4 5 .... n-1 n cout<<num;//输出随机数 return 0; }
生成随机小数
//#include<iostream>//提供输入输出cout cin //#include<cstdlib>//提供rand()、srand()随机函数 //#include<ctime>//提供time()时间函数,用来做随机种子 #include<bits/stdc++.h> using namespace std; int main(){ srand((unsigned)time(NULL));//设置随机种子:用系统当前时间当种子,如果不写会随机生成同一个数,放在main函数开头 double num=rand()*1.0/RAND_MAX;//RAND_MAX是系统最大值,把整数转成0-1之间的小数 cout<<fixed<<setprecision(5)<<num;//输出随机数,保留5位小数 return 0; }
批量生成多个整数随机数
//#include<iostream>//提供输入输出cout cin //#include<cstdlib>//提供rand()、srand()随机函数 //#include<ctime>//提供time()时间函数,用来做随机种子 #include<bits/stdc++.h> using namespace std; int main(){ srand((unsigned)time(NULL));//设置随机种子:用系统当前时间当种子,如果不写会随机生成同一个数,放在main函数开头 for(int i=1;i<=10;i++){//生成10个随机数 int num=rand()%55+1;//生成1-55的随机整数 cout<<num<<endl; } return 0; }