zoukankan      html  css  js  c++  java
  • hdu Can you solve this equation

    Can you solve this equation?

    Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 164 Accepted Submission(s): 94
    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!
    这道题用的是二分搜索法

    二分法原理

     给定方程f(x)=0,f(x)在区间[a,b]连续,且f(a)f(b)<0,则方程f(x)(a,b)

    至少有一根,为便于讨论,不妨设方程f(x)=0(a,b)内只有一实根    

    采取使有根区间逐步缩小,从而得到满足精度要求的实根     

    的近似值。   [a,b]区间二等分的中点x0 =(a+b)/2,

    f(x0)=0,x0f(x)=0的实根  f(a)f(b)<0 成立,

    则必在区间(a, x0),a1=a,b1= x0;

    否则必在区间(x0,b),a1= x0,b1=b,

    这样,得到新区间(a1,b1),其长度为[a,b]的一半,

    如此继续下去,进行k次等分后,得到一组不断缩小的区间,

    [a,b],[a1,b1],......[ak,bk].

     

    分析本题得:函数是一个单调递增的函数;所以此函数的0点只有一个。本题的精度为0.0001,保证小数点后前四位相同。

     1 #include <iostream>
    2 #include <stdio.h>
    3 #include <math.h>
    4 using namespace std;
    5 double y;
    6 double func(double x)
    7 {
    8 return 8*pow(x,4)+7*pow(x,3)+2*pow(x,2)+3*x+6;
    9 }
    10 int main()
    11 {
    12 int t;
    13 double left,right,mid,ans1,ans2,ans3;
    14 cin>>t;
    15 while(t--)
    16 {
    17 cin>>y;
    18 if(func(0)>y||func(100)<y)
    19 cout<<"No solution!"<<endl;
    20 else
    21 {
    22 left = 0.0;
    23 right = 100.0;
    24 mid = 50.0;
    25 ans1 = func(left)-y;
    26 ans2 = func(mid)-y;
    27 ans3 = func(right)-y;
    28 while(fabs(ans1-ans2)>0.0001)
    29 {
    30 if(ans2>0)
    31 {
    32 right = mid;
    33 ans3 = ans2;
    34 mid = (left+right)/2;
    35 }else
    36 {
    37 left = mid;
    38 ans1 = ans2;
    39 mid = (left+right);
    40 }
    41 ans2 = func(mid)-y;
    42 }
    43 printf("%.4f\n",mid);
    44 }
    45 }
    46 return 0;
    47 }

  • 相关阅读:
    Python运行时遇到UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 1: ordinal not in range(128)的问题
    Android 网络通信架构学习
    将Windows MyEclipse的web项目移植到Debian下
    build-essential : Depends: libc6-dev but it is not going to be installed or libc-dev 解决办法
    Debian可用的源 —— 23% waiting for headers解决办法
    将访问服务器的工作交由Service承担
    Servlet回传的数据显示在界面上
    Android客户端和Servlet服务器端通过JSON交互
    Welcome to My Blog!
    【三木夜话】无穷级的恐惧
  • 原文地址:https://www.cnblogs.com/newpanderking/p/2152439.html
Copyright © 2011-2022 走看看