使用 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

更新於: 2019-12-23

272 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告