# n个骰子点数和及各自出现的概率

f(n,s)=f(n-1,s-1)+f(n-1,s-2)+f(n-1,s-3)+f(n-1,s-4)+f(n-1,s-5)+f(n-1,s-6) ，0< n<=6n f(n,s)=0, s< n or s>6n

```#include <stdio.h>
#include <string.h>

#include <iostream>
using namespace std;

/****************************
func:获取n个骰子指定点数和出现的次数
para:n:骰子个数;sum:指定的点数和
return:点数和为sum的排列数
****************************/
int getNSumCount(int n, int sum){
if(n<1||sum<n||sum>6*n){
return 0;
}
if(n==1){
return  1;
}
int resCount=0;
resCount=getNSumCount(n-1,sum-1)+getNSumCount(n-1,sum-2)+
getNSumCount(n-1,sum-3)+getNSumCount(n-1,sum-4)+
getNSumCount(n-1,sum-5)+getNSumCount(n-1,sum-6);
return resCount;
}

//验证
int main(){
int n=0;
while(true){
cout<<"input dice num：";
cin>>n;
for(int i=n;i<=6*n;++i)
cout<<"f("<<n<<","<<i<<")="<<getNSumCount(n,i)<<endl;
}
}```

```/****************************************
func:给定骰子数目n，求所有可能点数和的种类数
para：n:骰子个数;count:存放各种点数和的种类数，下标i表示点数和为（i+n）
return:出错返回-1，成功返回0
****************************************/
int getNSumCountNotRecusion(int n, int* count){
if(n<1)
return -1;
//初始化最初状态
count[0]=count[1]=count[2]=count[3]=count[4]=count[5]=1;
if(n==1) return 0;

for(int i=2;i<=n;++i){
for(int sum=6*i;sum>=i;--sum){
int tmp1=((sum-1-(i-1))>=0?count[sum-1-(i-1)]:0); //上一阶段点数和sum-1的排列总数
int tmp2=(sum-2-(i-1)>=0?count[sum-2-(i-1)]:0);
int tmp3=(sum-3-(i-1)>=0?count[sum-3-(i-1)]:0);
int tmp4(sum-4-(i-1)>=0?count[sum-4-(i-1)]:0);
int tmp5=(sum-5-(i-1)>=0?count[sum-5-(i-1)]:0);
int tmp6=(sum-6-(i-1)>=0?count[sum-6-(i-1)]:0);
count[sum-i]=tmp1+tmp2+tmp3+tmp4+tmp5+tmp6;
}
}
return 0;
}

//验证
int main(){
int n;
while(true){
cout<<"iteration input dice num：";
cin>>n;
int* count=new int[5*n+1];
memset(count,0,(5*n+1)*sizeof(int));
getNSumCountNotRecusion(n,count);
int allCount=0;
for(int i=0;i<5*n+1;++i){
cout<<"f("<<n<<","<<i+n<<")="<<count[i]<<endl;
allCount+=count[i];
}
delete[] count;
}
}```

```    int total = pow((float)6, n);
for(int i = n; i <=6*n; ++i){   //n:骰子数目
float ratio = (float)getNSumCount(n,i)/total;
printf("%d: %f/n", i, ratio);
}  ```

# 参考文献

[1]剑指Offer.何海涛.电子工业出版社. [2]求n个骰子各点数和出现的概率-动态规划. [3]解题笔记(18)__n个骰子的点数.

470 篇文章39 人订阅

0 条评论

1774

2748

982

3801

29510

3548

2834

1373

2492

3342