n個のサイコロを地面に投げ、すべてのサイコロが上を向いている点数の和をsとする.nを入力して、sのすべての可能な出現に値する確率を印刷します

3104 ワード

一、アルゴリズムの説明
n個のサイコロを地面に投げ、すべてのサイコロが上を向いている点数の和をsとする.nを入力して、sのすべての可能な出現に値する確率を印刷します
二、アルゴリズム実現
/*************************************************************************
	> File Name: PrintProbability.c
	> Author: cyf
	> Mail: [email protected] 
	> Created Time: 2016 03 28      11 33 37 
 ************************************************************************/

#include "PrintProbability.h"

int g_maxvalue = 6;
int PrintProbability(int number)
{
	int ret = 0;
	if (number < 1)
	{
		ret = -1;
		return ret;
	}

	int maxvalue = number*g_maxvalue;
	int pProbability[maxvalue-number+1];
	int i;

	for(i=number; i<=maxvalue; i++)
		pProbability[i-number]=0;
	Probability(number, pProbability);

	int total = pow((double)g_maxvalue, (double)number);
	for(i=number; i<=maxvalue; i++)
	{
		double ratio = (double)pProbability[i-number]/total;
		printf("%d:%e
", i, ratio); } return ret; } int Probability(int number, int *pProbability) { int ret = 0; if (number < 1 || pProbability == NULL) { ret = -1; printf("func Probability() err:%d, input:%s", ret, "pProbability"); return ret; } int i; for(i=1; i<=g_maxvalue; i++) Prob(number, number, i, pProbability); return ret; } int Prob(int original, int current, int sum, int *pProbability) { int ret = 0; if (pProbability == NULL) { ret = -1; printf("func Probability() err:%d, input:%s", ret, "pProbability"); return ret; } int i; if(current==1) pProbability[sum-original]++; else { for(i=1;i<=g_maxvalue;i++) Prob(original, current-1, i+sum, pProbability); } return ret; }
/*************************************************************************
	> File Name: PrintProbability.h
	> Author: cyf
	> Mail: [email protected] 
	> Created Time: 2016 03 28      11 33 28 
 ************************************************************************/

#ifndef PRINTPROBABILITY_H
#define PRINTPROBABILITY_H

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

int PrintProbability(int number);
int Probability(int number, int *pProbability);
int Prob(int original, int current, int sum, int *pProbability);


#endif
/*************************************************************************
	> File Name: main.c
	> Author: cyf
	> Mail: [email protected] 
	> Created Time: 2016 03 28      11 33 48 
 ************************************************************************/

/*
 *  n       ,              s。  n,  s             
 * */

#include "PrintProbability.h"

int main()
{
	int ret = 0;
	int number = 2;
	ret = PrintProbability(number);
	if (ret == -1)
	{
		printf("func PrintProbability() err:%d,input:%d
", ret, number); } return 0; }
CC = gcc
CFLAGS = -g -lm

%.o:%.c
	$(CC) -o $@ -c $(CFLAGS) $<

main:main.o PrintProbability.o
	$(CC) main.o PrintProbability.o -o main $(CFLAGS)

clean:
	rm -rf *.o main