Program2_1001

来源:互联网 发布:英伦风男装品牌知乎 编辑:程序博客网 时间:2024/06/02 04:15

  我现在做的是第二专题的第一个试题,编号为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
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>
 
简单题意: 输入一个数Y,如果有一个数x(0<x<=100),使得8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,误差在1e-6以内,

解题思路:

  利用二分法进行计算,从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;
}


0 0
原创粉丝点击