(二分,精度控制)Can you solve this equation?--HDOJ

来源:互联网 发布:sas高校数据分析大赛 编辑:程序博客网 时间:2024/06/06 02:26

Can you solve this equation?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1343 Accepted Submission(s): 631

Problem Description
Now,given the equation 8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.

Input
The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);

Output

        For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.

Sample Input

2
100
-4

Sample Output

1.6152
No solution!

Author
Redow

Recommend
lcy

总结:
判断等号两边值是否相等,我是将右边的移到了左边,和零比较的时候,搞的我 很混乱,网上的解法是直接用等号左边的值与右边的值比较,是大是小,比较明了

函数是单调递增的,如果f(0) > 0 或者f(100) < 0 ,也就是左边函数的最小值就大于Y或者左边函数的最大值小于Y,都是没有结果的,直接no solution就可以了
如果确定有x存在,我们就用二分法来找就可以了

#include<iostream>#include<algorithm>#include<string.h>#include<stdio.h>#include<string>#include<math.h>using namespace std;double y;double f(double x){    return 8*pow(x,4) + 7*pow(x,3) + 2*x*x + 3*x + 6 - y;}int main(void){ //   freopen("in.txt","r",stdin);    int ncase;    cin >> ncase;    while(ncase--)    {        scanf("%lf",&y);        double st=0,ed=100,mid;        if(f(0) > 0.000001 || f(100) < 0.000001)        {            printf("No solution!\n");            continue;        }        while((ed-st) > 0.00000001)        {            mid = (ed + st) / 2;            if(f(mid) > 0.000001)                ed = mid;            else                st = mid;        }   //     cout << fabs(f(st,y)) <<endl;        printf("%.4lf\n",st);    }    return 0;}
阅读全文
0 0