面试题43 n个骰子的点数
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 void Print(int number) 6 { 7 if (number < 1) 8 return; 9 int *p[2]; 10 p[0] = new int[6 * number + 1]; 11 p[1] = new int[6 * number + 1]; 12 13 for (int i = 0; i < 6 * number + 1; i++) 14 { 15 p[0][i] = 0; 16 p[1][i] = 0; 17 } 18 int flag = 0; 19 for (int i = 1; i <= 6; i++) 20 { 21 p[flag][i] = 1; 22 } 23 for (int k = 2; k <= number; k++) 24 { 25 for (int i = 0; i < k; i++) 26 { 27 p[1 - flag][i] = 0; 28 } 29 30 for (int i = k; i <= 6 * k; i++) 31 { 32 p[1 - flag][i] = 0; 33 for (int j = 0; j <= i && j <= 6; j++) 34 { 35 p[1 - flag][i] += p[flag][i - j]; 36 } 37 } 38 flag = 1 - flag; 39 } 40 double total = pow(6.0, number); 41 for (int i = number; i <= 6 * number; i++) 42 { 43 double ratio = (double)p[flag][i] / total; 44 cout << i << ":" << ratio << endl; 45 } 46 delete[] p[0]; 47 delete[] p[1]; 48 49 } 50 51 int main() 52 { 53 Print(8); 54 return 0; 55 }