使用 C++ 计算掷 2 个骰子 N 次得到特定和的概率
给定一个和以及掷骰子对的次数 N 作为输入,任务是确定掷一对骰子 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
下面程序中使用的算法如下 −
- 输入和的值和 N,其中 N 表示掷骰子的次数
- 为了计算掷 2 个骰子 N 次出现该和的概率,应用以下公式:(有利情况/总情况) ^ 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; // function that calculates the Probability of getting a sum on throwing 2 Dices N times 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
广告