原文:

给定四个整数 abcd 。玩家 a & b 尝试点球得分。a 射击目标的概率为 a / b ,b 射击目标的概率为 c / d 。先罚点球的球员获胜。任务是找出 a 赢得比赛的概率。 举例:

输入: a = 1,b = 3,c = 1,d = 3 输出: 0.6 输入: a = 1,b = 2,c = 10,d = 11 输出: 0.52381

进场:如果我们考虑变量 k = a / b 为 a 击中目标的概率,r =(1 –( a/b))*(1–(c/d))为 a 和 b 都没有击中目标的概率。 因此,解形成几何级数k * r0 k * r1 k * r2 …..其和为(k/1–r)。将 kr 的值放在一起后,我们得到公式为k (1/(1 –( 1–r)(1–k))。 以下是上述方法的实施:

c

// c   implementation of the approach
#include 
using namespace std;
// function to return the probability of a winning
double getprobability(int a, int b, int c, int d)
{
    // p and q store the values
    // of fractions a / b and c / d
    double p = (double)a / (double)b;
    double q = (double)c / (double)d;
    // to store the winning probability of a
    double ans = p * (1 / (1 - (1 - q) * (1 - p)));
    return ans;
}
// driver code
int main()
{
    int a = 1, b = 2, c = 10, d = 11;
    cout << getprobability(a, b, c, d);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java implementation of the approach
class gfg
{
// function to return the probability
// of a winning
static double getprobability(int a, int b,
                             int c, int d)
{
    // p and q store the values
    // of fractions a / b and c / d
    double p = (double) a / (double) b;
    double q = (double) c / (double) d;
    // to store the winning probability of a
    double ans = p * (1 / (1 - (1 - q) *
                               (1 - p)));
    return ans;
}
// driver code
public static void main(string[] args)
{
    int a = 1, b = 2, c = 10, d = 11;
    system.out.printf("%.5f",
               getprobability(a, b, c, d));
}
}
// this code contributed by rajput-ji

python 3

# python3 implementation of the approach
# function to return the probability
# of a winning
def getprobability(a, b, c, d) :
    # p and q store the values
    # of fractions a / b and c / d
    p = a / b;
    q = c / d;
    # to store the winning probability of a
    ans = p * (1 / (1 - (1 - q) * (1 - p)));
    return round(ans,5);
# driver code
if __name__ == "__main__" :
    a = 1; b = 2; c = 10; d = 11;
    print(getprobability(a, b, c, d));
# this code is contributed by ryuga

c

// c# implementation of the approach
using system;
class gfg
{
// function to return the probability
// of a winning
public static double getprobability(int a, int b,
                                    int c, int d)
{
    // p and q store the values
    // of fractions a / b and c / d
    double p = (double) a / (double) b;
    double q = (double) c / (double) d;
    // to store the winning probability of a
    double ans = p * (1 / (1 - (1 - q) *
                               (1 - p)));
    return ans;
}
// driver code
public static void main(string[] args)
{
    int a = 1, b = 2, c = 10, d = 11;
    console.write("{0:f5}",
                   getprobability(a, b, c, d));
}
}
// this code is contributed by shrikant13

服务器端编程语言(professional hypertext preprocessor 的缩写)


java 描述语言


output: 

0.52381