把
n
个骰子扔在地上,所有骰子朝上一面的点数之和为
S
。输入
n
,
打印出 S 的所有可能的值出现的概率。
打印出 S 的所有可能的值出现的概率。
#include <stdio.h>
#include <math.h>
void SumProbabilityOfDices(int number, int* pProbabilities);
void SumProbabilityOfDices(int original, int current, int value, int tempSum, int* pProbabilities);
int g_maxValue = 6;
void PrintSumProbabilityOfDices(int number)
{
if(number < 1)
return;
int maxSum = number * g_maxValue;
int* pProbabilities = new int[maxSum - number + 1];
for(int i = number; i <= maxSum; ++i)
pProbabilities[i - number] = 0;
SumProbabilityOfDices(number, pProbabilities);
int total = pow((float)g_maxValue, number);
for(int i = number; i <= maxSum; ++i)
{
float ratio = (float)pProbabilities[i - number] / total;
printf("%d: %f\n", i, ratio);
}
}
void SumProbabilityOfDices(int number, int* pProbabilities)
{
for(int i = 1; i <= g_maxValue; ++i)
SumProbabilityOfDices(number, number, i, 0, pProbabilities);
}
void SumProbabilityOfDices(int original, int current, int value, int tempSum, int* pProbabilities)
{
if(current == 1)
{
int sum = value + tempSum;
pProbabilities[sum - original]++;
}
else
{
for(int i = 1; i <= g_maxValue; ++i)
{
int sum = value + tempSum;
SumProbabilityOfDices(original, current - 1, i, sum, pProbabilities);
}
}
}
int main()
{
PrintSumProbabilityOfDices(2);
return 0;
}