新手发帖,很多方面都是刚入门,有错误的地方请大家见谅,欢迎批评指正
<1>题问:伪随机数字和真正随机数字
<2>码代:
伪随机算法:
#include <iostream>
#include<ctime>
using namespace std;
double MyRandom(double start,double end)
{
return start+(end-start)*rand()/(RAND_MAX+1.0);
}
void main()
{
int a[10] = {0};
srand(unsigned(time(0)));
for(int i = 0;i < 1000000;i++)
{
int n = MyRandom(0,10);
switch(n)
{
case 0:
a[0]++;
break;
case 1:
a[1]++;
break;
case 2:
a[2]++;
break;
case 3:
a[3]++;
break;
case 4:
a[4]++;
break;
case 5:
a[5]++;
break;
case 6:
a[6]++;
break;
case 7:
a[7]++;
break;
case 8:
a[8]++;
break;
case 9:
a[9]++;
break;
}
}
for(i = 0;i < 10;i++)
cout<<a[i]*1.0/1000000<<endl;
}
真正随机算法:
#include <iostream>
#include <random>
using namespace std;
int main()
{
int count[11] = {0};
for(int i = 0;i < 1000000;i++)
{
std::random_device rd;
int num = rd()%10 + 1;
switch(num)
{
case 1:
count[1]++;
break;
case 2:
count[2]++;
break;
case 3:
count[3]++;
break;
case 4:
count[4]++;
break;
case 5:
count[5]++;
break;
case 6:
count[6]++;
break;
case 7:
count[7]++;
break;
case 8:
count[8]++;
break;
case 9:
count[9]++;
break;
case 10:
count[10]++;
break;
}
}
for(int i = 1;i <= 10;i++)
{
cout<<i<<"概率:"<<count[i]*1.0/1000000<<endl;
}
return 0;
}
<3>运行结果截图:
文章结束给大家分享下程序员的一些笑话语录: 腾讯总舵主马化腾,有人曾经戏称如果在Z国选举总统,马化腾一定当选,因为只要QQ来一个弹窗”投马总,送Q币”即可。