Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ความน่าจะเป็นที่จะได้รับผลรวมจากการโยน 2 Dices N ครั้งใน C++


เราได้รับผลรวมและจำนวนครั้งที่โยนลูกเต๋าคู่หนึ่งเป็นอินพุต และภารกิจคือการกำหนดความน่าจะเป็นที่จะได้รับผลรวมที่กำหนดจากการโยนลูกเต๋าสองครั้ง 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 ซึ่งระบุจำนวนครั้งที่โยนลูกเต๋า
  • สำหรับการคำนวณความน่าจะเป็นที่จะเกิดผลรวมในการโยนลูกเต๋า 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