此题是计算n个骰子扔在地上点数和出现的概率,可看作一个骰子扔了n次,计算所有可能结果出现的概率。
如果是2个骰子,共有36种组合,出现和为5的情况为(1,4)(2,3)(3,2)(4,1),其概率为4/36=0.111111
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:
**/
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
void Probability(int num)
{
int value[6] = { 1, 2, 3, 4, 5, 6 };
map<long long,long long> m;
for (int i = 0; i < 6; i++)
m[i + 1] = 1;
for (int i = 1; i < num ; i++)
{
map<long long,long long>::iterator it;
map<long long, long long> mtemp;
for (it = m.begin(); it != m.end(); it++)
{
for (int j = 0; j < 6; j++)
{
long long temp = it->first + value[j];
if (mtemp.count(temp) == 0)
mtemp[temp] = 1;
else
mtemp[temp] += 1;
}
}
//更新m字典
m.clear();
m = mtemp;
}
//计算概率并输出
map<long long, long long>::iterator it;
long long sum = pow(6, num);
for (it = m.begin(); it != m.end(); it++)
{
cout << it->first << " : " << it->second / (1.0*sum) << endl;
}
}
int main()
{
Probability(2);
system("pause");
return 0;
}