我现在做的是第二专题的第一个试题,编号为1001
试题内容如下所示:
Can you solve this equation?
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 75 Accepted Submission(s) : 25
2<br>100<br>-4<br>
1.6152<br>No solution!<br>
解题思路:
利用二分法进行计算,从0到100进行计算,设最大值为100,最小值为0,如果将最大值和最小值分别代入计算公式中,分别得到一个数据,两数据进行相减,如果值小于1e-6,结果就是(最大值+最小值)/2,否则,设一个中间值,即(最大值+最小值)/2,再判断中间值与y值的大小,如果比y大,则将最大值=中间值,反之,最小值=中间值,然后,再进行下一次循环,直到满足条件。
编写代码:
#include <iostream>
#include <cmath>
using namespace std;
double search(double x)
{
return 8*pow(x, 4)+7*pow(x,3)+2*pow(x,2)+3*x+6;
}
int main()
{
int n
cin >> n;
cout.precision(4);
while (n--)
{
int y;
double first, last, mid;
cin >> y;
if (search(0)<=y && search(100)>=y)
{
first = 0;
last = 100;
while (last-first>1e-6)
{
mid = (first+last)/2;
if(search(mid)>y)
last=mid;
else
first=mid;
}
cout << fixed << (last+last)/2 << endl;
}
else
cout << "No solution!" << endl;
}
return 0;
}