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
广告