/*
*
* 面试题43:n个骰子的点数
* 把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。
* 输入n,打印出s的所有可能的值出现的概率。
*
*/ #include <iostream>
#include <cmath> using namespace std; const int max_val = ; //核心,计算概率
//original为起始值,n个骰子起始值为n
//current为当前骰子个数
//骰子数之和
//和对应的次数
void probalility(int original, int current, int sum, int *probabilities)
{
if (current == ) {
probabilities[sum - original]++;
}
else{
//每个骰子都有六种可能
for (int i = ; i <= max_val; i++) {
probalility(original, current - , i + sum, probabilities);
}
}
}
//计算概率
void probalility(int number, int *probabilities)
{
for (int i = ; i <= max_val; i++) {
probalility(number, number, i, probabilities);
}
} void PrintPrabability(int number)
{
if (number < ) {
return;
}
//申请空间
int max_sum = number * max_val;
int *probabilities = new int[max_sum];
for (int i = number; i <= max_sum; i++) {
probabilities[i] = ;
}
//计算可能的情况
probalility(number, probabilities); //计算概率
int total = pow(double(max_val), number);
for (int i = number; i <= max_sum; i++) {
double ratio = (double)probabilities[i - number] / total;
cout << i << " " << ratio << endl;
}
}