码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-09 13:59:42      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:方法   post   ted   打印   ring   blog   有一个   data-   img   

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


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


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


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


代码:

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>


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)

标签:方法   post   ted   打印   ring   blog   有一个   data-   img   

原文地址:http://www.cnblogs.com/cxchanpin/p/7141136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!