課程練習二-1001

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;<br>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<br>100<br>-4<br>
 

Sample Output
1.6152<br>No solution!<br>
 

Author

Redow


題意:已知Y,根據公式 8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y  求出x 。(保留4位小數)


思路:這題難在 保留小數,用暴力搜索的話,會超時且x 未必準確。(可以自己找數據分析)

so 用 二分法。


提交總是錯,求改正。第二題和這道類似,那道過了,這道沒過。


代碼:

#include<iostream>
#include<string.h>
#include<cmath>
#include<iomanip>
#include<algorithm>
using namespace std;


int main()
{
int T;
cin >> T;
for (int i = 0; i < T; i++)
{
int Y;
cin>>Y; 
bool flag=false;
double j=0,k=100,m=100;
while((k-j)>0.000001)
{
    m=(j+k)/2;
    if(8*m*m*m*m+7*m*m*m+2*m*m+3*m+6==Y)
    {
         cout<<setprecision(4)<<fixed<<m<<endl;
         flag=true;
     break;
    }    
    else if(8*m*m*m*m+7*m*m*m+2*m*m+3*m+6>Y)
    {
    k=m;
    }
    else 
    {
    j=m;
    }
}
if(!flag)
cout << "No solution!" << endl;

 
}
system("pause");
return 0;
}



AC:

#include <iostream>
#include<cmath>
#include<iomanip>
using namespace std;


double find(double x)
{
return 8 * pow(x, 4) + 7 * pow(x, 3) + 2 * pow(x, 2) + 3 * x + 6;
}
int main()
{
int t;
double y, f, l, mid;
cin >> t;
while (t--)
{
cin >> y;
if (find(0) <= y && find(100) >= y)
{
f = 0;
l = 100;
while (l - f>1e-6)
{
mid = (f + l) / 2;
if (find(mid)>y)
l = mid;
else
f = mid;
}
cout << setprecision(4) << fixed << (f + l) / 2 << endl;
}
else
cout<<"No solution!"<<endl;
}

        system("pause");
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章