<span style="font-weight: bold; font-size: 18pt;"><span style="font-size: 24px; text-align: center; color: green;"><strong>B - </strong></span><span style="color: rgb(0, 0, 255); font-size: 24px; text-align: center;"><strong>Can you solve this equation?</strong></span>
</span>
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
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.
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!
这道题的实质其实也是给定一个区间,要求在区间中找到符合要求的值,所以也用二分法来解答。当中值与给定值之间的差距小到一定精度时即可输出。
启示: 1.学习到先用一个函数来保存复杂的算术公式,可以大大提高编写代码的简便性。
2.注意保留小数点后若干位的写法。
代码:
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int T;
double l,r,mid,x,Y,t=1e-8;
double v(double x){
return 8.0*x*x*x*x + 7.0*x*x*x + 2.0*x*x + 3.0*x + 6.0 ;
}
int main(){
cin>>T;
while(T--){
cin>>Y;
l=0; r=100;
if((v(0)-Y>0)||(v(100.0)-Y<0))
{
cout<<"No solution!"<<endl;
break;}
while(l<r){
mid=(l+r)/2;
if(fabs(v(mid)-Y)<t)
break;
else if(v(mid)-Y<0)
l=mid;
else
r=mid;
}
mid=(l+r)/2;
printf("%.4lf\n",mid);
}
return 0;
}