题目:把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。
思路:在一轮循环当中,第一个数组总的第n个数字表示骰子和为n出现的次数。在下一轮循环中,我们加上一个新的骰子,此时和为n的骰子出现的次数应该等于上一轮循环中点数和为n-1,n-2,n-3,n-4,n-5,n-6的次数的总和(新的骰子可能投出1~6)。(基于循环,时间性能好)
#include <iostream>
#include <vector>
using namespace std;
void probability(int num);
int g_maxValue = 6;
int main() {
probability(10);
system("pause");
return 0;
}
void probability(int num) {
if (num < 1)return;
int *pProbabilities[2];
//
pProbabilities[0] = new int[g_maxValue*num + 1];
pProbabilities[1] = new int[g_maxValue*num + 1];
for (int i = 0; i != g_maxValue * num + 1; i++) {
pProbabilities[0][i] = 0;
pProbabilities[1][i] = 0;
}
int flag = 0;
//初始化一个骰子的情况
for (int i = 1; i <= g_maxValue; i++) {
pProbabilities[flag][i] = 1;
}
for (int i = 2; i <= num; i++) {
//把另一个数组中的不可能出现的和置零
for (int j = 0; j < i; j++) {
pProbabilities[1 - flag][j] = 0;
}
for (int j = i; j <= g_maxValue * num; j++) {
pProbabilities[1 - flag][j] = 0;
for (int k = 1; k <= g_maxValue && k <= j; k++) {
pProbabilities[1 - flag][j] += pProbabilities[flag][j - k];
}
}
flag = 1 - flag;
}
double total = pow(static_cast<double>(g_maxValue), num);
for (int i = num; i <= g_maxValue * num; i++) {
double ratio = static_cast<double>(pProbabilities[flag][i]) / total;
cout << i << " : " <<ratio << endl;
}
delete[] pProbabilities[0];
delete[] pProbabilities[1];
}
参考博文:
https://blog.csdn.net/m0_37950361/article/details/82153175