编程算法 - n个骰子的点数(递归) 代码(C)

n个骰子的点数(递归) 代码(C)


本文地址: http://blog.csdn.net/caroline_wendy


题目: 把n个骰子仍在地上, 全部骰子朝上一面的点数之和为s. 输入n, 打印出s的全部可能的值出现的概率.


採用递归的方法, 能够如果仅仅有一个骰子, 然后骰子数递增相加.


代码:

/*
 * main.cpp
 *
 *  Created on: 2014.7.12
 *      Author: spike
 */

#include 
#include 
#include 
#include 


using namespace std;


const int g_maxValue = 6;


void Probability (int original, int current, int sum, int* pProbabilities) {
	if (current == 1) {
		pProbabilities[sum-original]++;
	} else {
		for(int i=1; i<=g_maxValue; ++i) {
			Probability(original, current-1, i+sum, pProbabilities);
		}
	}
}


void Probability (int number, int* pProbabilities) {
	for	(int i=1; i<=g_maxValue; ++i)
		Probability(number, number, i, pProbabilities);
}


void PrintProbability (int number) {
	if (number < 1)
		return;
	int maxSum = number*g_maxValue;
	int* pProbabilities = new int[maxSum-number+1];
	for (int i=number; i<=maxSum; ++i)
		pProbabilities[i-number] = 0;
	Probability(number, pProbabilities);
	int total = pow((double)g_maxValue, number);
	for (int i=number; i<= maxSum; ++i) {
		double ratio = (double)pProbabilities[i-number] / total;
		printf("%d: %e\n", i, ratio);
	}
	delete[] pProbabilities;
}


int main(void)
{
    PrintProbability(2);
    return 0;
}




输出:

2: 2.777778e-002
3: 5.555556e-002
4: 8.333333e-002
5: 1.111111e-001
6: 1.388889e-001
7: 1.666667e-001
8: 1.388889e-001
9: 1.111111e-001
10: 8.333333e-002
11: 5.555556e-002
12: 2.777778e-002




编程算法 - n个骰子的点数(递归) 代码(C)_第1张图片




你可能感兴趣的:(编程算法 - n个骰子的点数(递归) 代码(C))