C++中第N+1天的降雨機率
給定一個包含0和1的陣列,其中0表示無雨,1表示雨天。任務是計算第N+1天的降雨機率。
為了計算第N+1天的降雨機率,我們可以應用以下公式:
集合中雨天的總數 / 總天數
輸入
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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP