剑指Offer43 n个骰子点数概率
Posted Juntaran
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指Offer43 n个骰子点数概率相关的知识,希望对你有一定的参考价值。
1 /************************************************************************* 2 > File Name: 43_Dics.cpp 3 > Author: Juntaran 4 > Mail: [email protected] 5 > Created Time: 2016年09月04日 星期日 16时46分00秒 6 ************************************************************************/ 7 8 #define maxNum 6 // 骰子最多为6 9 10 #include <stdio.h> 11 #include <math.h> 12 13 void PrintDics(int number) 14 { 15 if (number < 1) 16 return; 17 18 int* Probabilities[2]; 19 Probabilities[0] = new int[maxNum * number + 1]; 20 Probabilities[1] = new int[maxNum * number + 1]; 21 22 23 for (int i = 0; i < maxNum*number+1; ++i) 24 { 25 Probabilities[0][i] = 0; 26 Probabilities[1][i] = 0; 27 } 28 int flag = 0; 29 for (int i = 1; i <= maxNum; ++i) 30 Probabilities[flag][i] = 1; 31 32 33 for (int k = 2; k <= number; ++k) 34 { 35 for (int i = 0; i < k; ++i) 36 Probabilities[1-flag][i] = 0; 37 for (int i = k; i <= maxNum*k; ++i) 38 { 39 Probabilities[1-flag][i] = 0; 40 for (int j = 1; j<=i&&j<=maxNum; ++j) 41 Probabilities[1-flag][i] += Probabilities[flag][i-j]; 42 } 43 flag = 1 - flag; 44 } 45 46 double total = pow((double)maxNum, number); 47 for (int i = number; i <= maxNum*number; ++i) 48 { 49 double ratio = (double)Probabilities[flag][i] / total; 50 printf("%d: %f\n", i, ratio); 51 } 52 delete[] Probabilities[0]; 53 delete[] Probabilities[1]; 54 } 55 56 int main() 57 { 58 int number = 5; 59 PrintDics(number); 60 }
以上是关于剑指Offer43 n个骰子点数概率的主要内容,如果未能解决你的问题,请参考以下文章