UVA - 10341 Solve It (数学--二分法求解)

来源:互联网 发布:想听歌下载什么软件 编辑:程序博客网 时间:2024/06/03 08:41

大体题意:

给你一个函数,给你定义域,求出是否有解,有解输出解,无解输出 No solution

思路:

分析式子和输入  知道这个式子是一个单调递减的,那么就可以用二分了!

当两个端点 的函数值乘积大于0时,说明同号,则无解!

否则有唯一解!  直接二分找就可以了!

教训:

这种求解方程的二分,涉及到小数的二分 ,最好用循环多少来解,不要用l < r  容易出错!!

#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<cstdlib>using namespace std;double p,q,r,s,t,u;const double e =  2.718281828459045;const double eps = 1e-10;double f(double x){return p*pow(e,-x) + q*sin(x) + r * cos(x) + s*tan(x) + t * x * x + u;}int main(){while(scanf("%lf %lf %lf %lf %lf %lf",&p, &q, &r, &s, &t, &u) == 6){if (fabs(f(1)) < eps)printf("1.0000\n");else if (fabs(f(0)) < eps)printf("0.0000\n");else if (f(1) * f(0) > eps)printf("No solution\n");else {double l = 0;double r = 1;for (int i = 0; i < 100; ++i){double mid = (l + r) / 2.0;if (f(mid) > 0)l = mid;else r = mid;}printf("%.4lf\n",(l+r)/2.0);}}return 0;}


0 0
原创粉丝点击