点数和

#include <iostream>
#include <time.h>
#include <vector>
#include <assert.h>
#include <list>
#include <math.h>
using namespace std;

//计算n个骰子某次投掷点数和为s的出现次数
int CountNumber(int n, int s) {
	//n个骰子点数之和范围在n到6n之间,否则数据不合法
	if(s < n || s > 6*n) 
		return 0;
	//当有一个骰子时,一次骰子点数为s(1 <= s <= 6)的次数当然是1
	if(n == 1) 
		return 1;
	else
		return CountNumber(n-1, s-6) + CountNumber(n-1, s-5) + CountNumber(n-1, s-4) + 
		          CountNumber(n-1, s-3) +CountNumber(n-1, s-2) + CountNumber(n-1, s-1);
}
void listDiceProbability(int n) {
	int i=0;
	unsigned int nTotal = pow((double)6, n);
	for(i = n; i <= 6 * n; i++) {
		printf("P(s=%d) = %d/%d\n", i, CountNumber(n,i), nTotal);
	}
}

int main() {
	listDiceProbability(3);
}
发布了345 篇原创文章 · 获赞 8 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/ailinyingai/article/details/103933392