Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 2개의 주사위를 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

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다. -

  • 주사위를 던진 횟수를 나타내는 sum과 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