กำหนดด้วยอาร์เรย์ที่ประกอบด้วย 0 และ 1 โดยที่ 0 หมายถึงไม่มีฝนและ 1 หมายถึงวันที่ฝนตก งานคือการคำนวณความน่าจะเป็นของฝนในวันที่ N+1
ในการคำนวณความน่าจะเป็นของฝนในวันที่ N+1 เราสามารถใช้สูตรได้
รวมจำนวนวันฝนตกในชุด / จำนวนวันทั้งหมดใน a
ป้อนข้อมูล
arr[] = {1, 0, 0, 0, 1 } ผลผลิต
probability of rain on n+1th day : 0.4
คำอธิบาย
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
ป้อนข้อมูล
arr[] = {0, 0, 1, 0} ผลผลิต
probability of rain on n+1th day : 0.25
คำอธิบาย
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
แนวทางที่ใช้ในโปรแกรมมีดังนี้
-
ใส่องค์ประกอบของอาร์เรย์
-
ใส่ 1 แทนวันฝนตก
-
ใส่ 0 แทนวันที่ไม่มีฝน
-
คำนวณความน่าจะเป็นโดยใช้สูตรที่ให้ไว้ด้านบน
-
พิมพ์ผลลัพธ์
อัลกอริทึม
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 ตัวอย่าง
#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;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
probability of rain on n+1th day : 0.4