Được đưa ra với một mảng chứa số 0 và số 1 trong đó số 0 biểu thị không có mưa và số 1 biểu thị ngày mưa. Nhiệm vụ là tính toán xác suất mưa vào ngày thứ N + 1.
Để tính xác suất mưa vào ngày thứ N + 1, chúng ta có thể áp dụng công thức
Tổng số ngày mưa trong tập hợp / tổng số ngày trong một
Đầu vào
arr[] = {1, 0, 0, 0, 1 } Đầu ra
probability of rain on n+1th day : 0.4
Giải thích
total number of rainy and non-rainy days are: 5 Total number of rainy days represented by 1 are: 2 Probability of rain on N+1th day is: 2 / 5 = 0.4
Đầu vào
arr[] = {0, 0, 1, 0} Đầu ra
probability of rain on n+1th day : 0.25
Giải thích
total number of rainy and non-rainy days are: 4 Total number of rainy days represented by 1 are: 1 Probability of rain on N+1th day is: 1 / 4 = 0.25
Phương pháp tiếp cận được sử dụng trong chương trình nhất định như sau
-
Nhập các phần tử của một mảng
-
Đầu vào 1 để biểu thị ngày mưa
-
Nhập 0 để biểu thị ngày không mưa
-
Tính xác suất bằng cách áp dụng công thức đã cho ở trên
-
In kết quả
Thuật toán
Start
Step 1→ Declare Function to find probability of rain on n+1th day
float probab_rain(int arr[], int size)
declare float count = 0, a
Loop For int i = 0 and i < size and i++
IF (arr[i] == 1)
Set count++
End
End
Set a = count / size
return a
step 2→ In main()
Declare int arr[] = {1, 0, 0, 0, 1 }
Declare int size = sizeof(arr) / sizeof(arr[0])
Call probab_rain(arr, size)
Stop Ví dụ
#include <bits/stdc++.h>
using namespace std;
//probability of rain on n+1th day
float probab_rain(int arr[], int size){
float count = 0, a;
for (int i = 0; i < size; i++){
if (arr[i] == 1)
count++;
}
a = count / size;
return a;
}
int main(){
int arr[] = {1, 0, 0, 0, 1 };
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"probability of rain on n+1th day : "<<probab_rain(arr, size);
return 0;
} Đầu ra
Nếu chạy đoạn mã trên, nó sẽ tạo ra kết quả sau -
probability of rain on n+1th day : 0.4