题目:
把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。
题解:
使用两个数组存每次投的点数
1 void theProbability(const int &num) 2 { 3 if (num < 1)return ; 4 vector<vector<int>> theSum(2, vector<int>(6 * num + 1, 0)); 5 int flag = 0; 6 for (int i = 1; i <= 6; ++i)theSum[flag][i] = 1;//第一次投,每个数的概率相同 7 for (int i = 2; i <= num; ++i)//骰子数 8 { 9 //for (int j = 0; j < i; ++j)theSum[1-flag][j] = 0;//前面投过的清零 10 for (int j = i; j <= 6 * i; ++j) 11 { 12 theSum[1 - flag][j] = 0; 13 for (int k = 1; k <= j && k <= 6; ++k) 14 theSum[1 - flag][j] += theSum[flag][j - k]; 15 } 16 flag = 1 - flag; 17 } 18 for (int i = num; i <= num * 6; ++i) 19 cout << i << ": " << (double)theSum[flag][i] / (double)(pow(6.0, num)) << endl; 20 }