本文实例讲述了C++实现N个骰子的点数算法,分享给大家供大家参考之用。具体方法如下:
题目要求:把n个骰子仍在地上,所有点数
实现代码如下:
#include <iostream> using namespace std; const int g_maxValue = 6; const int number = 6; int array[(number - 1) * g_maxValue + 1]; void probility(int original, int current, int sum, int *array) { if (current == 0) { array[sum - original]++; return; } for (int i = 1; i <= g_maxValue; i++) { probility(original, current - 1, sum + i, array); } } void generateValue(int *array, int size) { if (array == NULL || size <= 0) return; for (int i = number; i <= number * g_maxValue; i++) { array[i - number] = 0; } probility(number, number, 0, array); for (int i = 0; i < (number - 1) * g_maxValue + 1; i++) { cout << array[i] << " "; } } void main() { generateValue(array, (number - 1) * g_maxValue + 1); }
采用循环解法,和上述代码本质一样,但是略有不同。
具体实现代码如下:
#include <iostream> using namespace std; void PrintProbability(int number) { const int g_maxValue = 6; int *array[2]; for (int i = 0; i < 2; i++) { array[i] = new int[g_maxValue * number]; } for (int i = 0; i < g_maxValue * number; i++) { array[0][i] = 0; array[1][i] = 0; } int flag = 0; for (int i = 0; i < g_maxValue; i++) { array[flag][i] = 1; } for (int i = 1; i < number; i++) { for (int j = 0; j < i; j++) array[1 - flag][j] = 0; for (int j = i; j < (i + 1) * g_maxValue; j++) { array[1 - flag][j] = 0; for (int k = 1; k <= j && k <= g_maxValue; k++) array[1 - flag][j] += array[flag][j - k]; } flag = 1 - flag; } for (int i = number - 1; i < g_maxValue * number; i++) { cout << array[flag][i] << " "; } } void main() { PrintProbability(2); }
希望本文所述对大家C++程序算法设计的学习有所帮助。