问题描述:有N个骰子,同时掷出,计算向上面数字之和以及出现的概率(5位小数)。
思路:这是一个组合问题,点数和是如何组合得出的,这里用递归实现。
#include<iostream>
using namespace std;
void fun1(int k, int detph, int &sumSum, int tmpSum,int sum[]){
tmpSum += k;
--detph;
if(detph<=0){
sum[tmpSum] += 1;
sumSum++;
return;
}
for(int i=k; i<=6; i++){
fun1(i, detph,sumSum,tmpSum, sum);
}
}
int main(){
int n=0;
cin>>n;
int sum[6*n+1];
memset(sum,0,(6*n+1)*sizeof(int));
int sumSum = 0;
int tmpSum = 0;
int detph = n;
for(int i=1; i<=6; i++){
fun1(i, detph,sumSum,tmpSum, sum);
}
cout.precision(5);//控制位数
cout<<"[";
for(int i = n; i <= 6*n; ++i){
cout<<"["<<i<<",";
cout<<fixed<<(double)sum[i]/sumSum;
cout<<"]";
if(i < 6*n) cout<<",";
}
cout<<"]"<<endl;
}