标签:rand 练习 int Random seed 随机数 include srand
一、 初步了解
1. setw(int n)
头文件:#include<iomanip>
占位函数,处理输出间隔的问题,占n个位,不足的用空格补充
2. rand( )
头文件:#include<cstdlib>
rand( ) %n:产生【0,n-1】 的随机数;
rand( ) %n+1:产生【1,n】的随机数;
程序1:
#include <iostream>
#include<iomanip> //cintains the fuction prototype for setw
#include<cstdlib> //contains the fuction prototype for rand
using namespace std;
int main(){
for(int i =1;i<=20;i++){
cout << setw(10) << (rand()%6+1);
if(i%5==0) cout <<endl;
}
}
6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1
二、掷骰子
#include <iostream>
#include <cstdlib>
#include<iomanip>
using namespace std;
int main()
{
int f1=0; //每面出现的次数
int f2=0;
int f3=0;
int f4=0;
int f5=0;
int f6=0;
for(int roll=1;roll<=60;roll++){ //掷骰子60次
int face=1+rand()%6; //记录每次掷骰子掷导的面数
switch(face){
case 1:
f1++;break;
case 2:
f2++;break;
case 3:
f3++;break;
case 4:
f4++;break;
case 5:
f5++;break;
case 6:
f6++;break;
default:cout <<"Program should never get here!"<<endl;
}
}
cout <<"Face"<<setw(13)<<"Frequency"<<endl;
cout <<" 1"<<setw(13)<<f1;
cout <<"\n 2"<<setw(13)<<f2;
cout <<"\n 3"<<setw(13)<<f3;
cout <<"\n 4"<<setw(13)<<f4;
cout <<"\n 5"<<setw(13)<<f5;
cout <<"\n 6"<<setw(13)<<f6;
return 0;
}
三、srand(unsigned int seed)函数
1. rand辨析
rand()产生的是伪随机数:有规律可循的随机数,程序每次调用都会重复执行刚才的产生数序列
函数在调用时,自动设置种子数seed=1;种子数相同,产生的随机数序列也相同
2.srand(unsigned int seed)
srand(int seed) :设置rand函数的种子值,产生真正的、无逻辑可循的随机数
头文件:#include<cstdlib>
srand()用来设置rand()产生随机数时的随机数种子。参数seed是整数,通常可以利用time(0)或geypid(0)的返回值作为seed。
程序2:
在一的基础上用srand设置了seed值
#include <iostream>
#include <cstdlib>
#include<iomanip>
using namespace std;
int main()
{
unsigned seed;
cout<<"Enter seed"<<endl;
cin>>seed;
srand(seed);
//与程序一相同,设置了seed值后,每次运行产生的随机数都不一样
for(int i =1;i<=20;i++){
cout << setw(10) << (rand()%6+1);
if(i%5==0) cout <<endl;
}
return 0;
}
四、掷骰子:使用srand(time(0))和枚举类型
标签:rand,练习,int,Random,seed,随机数,include,srand 来源: https://blog.csdn.net/weixin_45662399/article/details/115342701
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。