题
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is
for SmallR while
for Zanoes. The one who shoots in the target first should be the winner.
Output the probability that SmallR will win the match.
Input
A single line contains four integers
.
Output
Print a single real number, the probability that SmallR will win the match.
The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Sample test(s)
input
代码语言:javascript复制1 2 1 2
output
代码语言:javascript复制0.666666666667
题意:给出两个弓箭手的射中目标的概率(分数),两人轮流射击,求第一位弓箭手赢的概率(小数)
分析:第一位弓箭手赢,那么第一次就射中或者,第一次不中而第二个弓箭手也不中,第二次中,……
p=a/b为第一位射中的概率,q=c/d为第二位射中的概率。
题目要求误差小于1e-6,刚开始我的代码是下面这样
代码语言:javascript复制#include<stdio.h>
int main(){
double a,b,c,d,ans,u;
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
ans=1;u=1;
while(u*a/b>=1e-6){//改成-7、-8也会WA,-9可过
u*=(1-a/b)*(1-c/d);
ans =u;
}
printf("%lfn",ans*a/b);
return 0;
}
因为当u*a/b<1e-6时ans继续加下去,可能比当前ans大不止1e-6,因为后面加了好几次;正确的方法是用等比数列求和公式
s=(1-qn)/(1-q),当n趋于无穷时,因为0<q<1,所以s=1/(1-q)
q=(1-a/b)*(1-c/d),ans=s*a/b.
代码语言:javascript复制#include<stdio.h>
int main(){
double a,b,c,d,ans,u;
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
ans=1/(1-(1-a/b)*(1-c/d));
printf("%.12lfn",ans*a/b);
return 0;
}
进行化简一下得到
代码语言:javascript复制#include<stdio.h>
int main(){
double a,b,c,d,ans,u;
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
printf("%.12lfn",a*d/(a*d b*c-a*c));
return 0;
}