在C ++中N次抛出2个骰子得到求和的概率
我们得到了掷骰子对作为输入的总和和次数,任务是确定在掷骰子N次后获得给定总和的概率。
概率是从可用数据集中获得所需输出的机会。概率范围在0和1之间,其中整数0表示不可能的可能性,而整数1表示确定性。
示例
Input-: sum = 12, N = 1 Output-: Probability = 1/36 Explanation-: if a pair of dice is thrown once then the combinations will be (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6). Out of these combinations we can get sum 12 at pair (6, 6) only therefore probability would be 1/36 Input-: sum = 4 and N = 6 Output-: probability is : 1/2985984
以下程序中使用的方法如下-
输入sum和N的值,N表示掷骰子的次数
为了计算N次投掷2个骰子时发生总和的概率,请应用以下公式:( 有利/总计)^N
现在计算投掷2个骰子1次的总和发生的概率,让我们得出1
用于计算发生投掷2个骰子的总和N次的概率为-
概率2=(概率1)^N.即,概率1提高到幂N
算法
Start
Step 1-> declare function to calculate the probability
int probability(int sum, int times)
Declare and set float res = 0.0 and total = 36.0
Declare and set long int probab = 0
Loop For i = 1 and i <= 6 and i++
Loop For j = 1 and j <= 6 and j++
IF ((i + j) = sum)
Set res++
End
End
End
Declare and set int gcd1 = __gcd((int)res, (int)total)
Declare and set res = res / (float)gcd1
Set total = total / (float)gcd1
Set probab = pow(total, times)
return probab
Step 2-> In main() Declare and set int sum = 4 and times = 6
Call probability(sum, times)
Stop示例
#include <bits/stdc++.h>
using namespace std;
//计算N次投掷2次骰子时求和的概率的函数
int probability(int sum, int times) {
float res = 0.0, total = 36.0;
long int probab = 0;
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 6; j++) {
if ((i + j) == sum)
res++;
}
}
int gcd1 = __gcd((int)res, (int)total);
res = res / (float)gcd1;
total = total / (float)gcd1;
probab = pow(total, times);
return probab;
}
int main() {
int sum = 4, times = 6;
cout<<"probability is : ";
cout << "1" << "/" << probability(sum, times);
return 0;
}输出结果
probability is : 1/2985984
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短