一个屋子里人数必须达到多少人,才能使其中两个人生日相同的机会达到50%
根据wiki中的伪代码编写的代码
伪代码为
c++代码为
#include <iostream>
using namespace std;
int main()
{
int days=365;
int numberPeople=1;
double probility=0;
while(probility<0.5)
{
numberPeople++;
probility=1-((1-probility)*(days-(numberPeople-1))/days);
}
cout<<"365天中人数达到"<<numberPeople<<"时其中两个人生日相同的机会达到50%";
return 0;
}
运行结果
升级版
可以测试多个天数,比如说一年只有300(可以为其它天数,以变量days代替)天,屋子里人数必须达到多少人,才能使其中两个人生日相同的机会达到50%,c++代码
#include <iostream>
using namespace std;
int main()
{
int testnumber,days,numberPeople;
double probility;
cout<<"请输入想测试的次数"<<endl;
cin>>testnumber;
while(testnumber--)
{
cout<<"请输入天数"<<endl;
cin>>days;
probility=0;
numberPeople=1;
while(probility<0.5)
{
numberPeople++;
probility=1-((1-probility)*(days-(numberPeople-1))/days);
}
cout<<days<<"天中人数达到"<<numberPeople<<"时其中两个人生日相同的机会达到50%"<<endl;
}
return 0;
}
运行结果