原文:
给定 1 和 0 的数组,其中 a i = 1 表示我第天是雨天,a i = 0 表示不是雨天。任务是找到第 n 1 次是雨天的概率。 举例:
输入: a[] = {0,0,1,0} 输出: .25 由于 4 天中有一天下雨,因此 5 第天的概率为 0.25 输入: a[] = {1,0,1,0,1,1,1} 输出: 0.71
第 n 1天下雨的概率可以用下面的公式计算出来:
probability = *number of rainy days / total number of days.*
首先计算 1 的个数,然后概率将是 1 的个数除以 n,即 count/n 下面是上述方法的实现:
c
// c code to find the probability of rain
// on n 1-th day when previous day's data is given
#include
using namespace std;
// function to find the probability
float raindayprobability(int a[], int n)
{
float count = 0, m;
// count 1
for (int i = 0; i < n; i ) {
if (a[i] == 1)
count ;
}
// find probability
m = count / n;
return m;
}
// driver code
int main()
{
int a[] = { 1, 0, 1, 0, 1, 1, 1, 1 };
int n = sizeof(a) / sizeof(a[0]);
cout << raindayprobability(a, n);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java code to find the
// probability of rain
// on n 1-th day when previous
// day's data is given
import java.io.*;
import java.util.*;
class gfg
{
// function to find
// the probability
static float raindayprobability(int a[],
int n)
{
float count = 0, m;
// count 1
for (int i = 0; i < n; i )
{
if (a[i] == 1)
count ;
}
// find probability
m = count / n;
return m;
}
// driver code
public static void main(string args[])
{
int a[] = { 1, 0, 1, 0, 1, 1, 1, 1 };
int n = a.length;
system.out.print(raindayprobability(a, n));
}
}
python 3
# python 3 program to find
# the probability of rain
# on n 1-th day when previous
# day's data is given
# function to find the probability
def raindayprobability(a, n) :
# count occurence of 1
count = a.count(1)
# find probability
m = count / n
return m
# driver code
if __name__ == "__main__" :
a = [ 1, 0, 1, 0, 1, 1, 1, 1]
n = len(a)
# function calling
print(raindayprobability(a, n))
# this code is contributed
# by ankitrai1
c
// c# code to find the
// probability of rain
// on n 1-th day when
// previous day's data
// is given
using system;
class gfg
{
// function to find
// the probability
static float raindayprobability(int []a,
int n)
{
float count = 0, m;
// count 1
for (int i = 0; i < n; i )
{
if (a[i] == 1)
count ;
}
// find probability
m = count / n;
return m;
}
// driver code
public static void main()
{
int []a = {1, 0, 1, 0,
1, 1, 1, 1};
int n = a.length;
console.writeline(raindayprobability(a, n));
}
}
// this code is contributed
// by inder_verma.
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
output:
0.75
时间复杂度: o(n)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处