uva 10341 Solve It
二分法,注意端点精度0.00001是过不了的……1e-9差不多吧……
#include<stdio.h> #include<math.h> double a1,a2,p,q,r,s,t,u; double f(double x) { double ans=p*exp(-x)+q*sin(x)+r*cos(x)+s*tan(x)+t*x*x+u; return ans; } int main() { double ans; while(~scanf("%lf%lf%lf%lf%lf%lf",&p,&q,&r,&s,&t,&u)) { a1=0;a2=1; if(f(0)<0&&f(1)<0) printf("No solution\n"); else if(f(0)>0&&f(1)>0) printf("No solution\n"); else { while(a2-a1>=0.000000001) { ans=(a2-a1)/2; if(f(ans+a1)>0) { if(f(a1)<0) a2=ans+a1; else a1=ans+a1; } else { if(f(a1)<0) a1=ans+a1; else a2=ans+a1; } } printf("%.4f\n",a1); } } return 0; }
简化版
#include<stdio.h> #include<math.h> double p,q,r,s,t,u; double f(double x) { double ans=p*exp(-x)+q*sin(x)+r*cos(x)+s*tan(x)+t*x*x+u; return ans; } int main() { double a1,a2,ans,k; while(~scanf("%lf%lf%lf%lf%lf%lf",&p,&q,&r,&s,&t,&u)) { a1=0;a2=1; if(f(0)*f(1)>0) printf("No solution\n"); else { while(a2-a1>0.000000001) { ans=a1+(a2-a1)/2; k=f(ans); if(k<0) a2=ans; else a1=ans; } printf("%.4lf\n",a1); } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/