概述:现在给出方程式8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,给定Y的值,求在0-100之间使得方程成立的X的值。
思路:给定Y值之后,从0开始递增X的值,利用二分法求对应的中值,并利用方程求出对应的Y'的值,不断重复比较,得出最符合题意的值。
感想:高中时数学有讲过二分法的概念,可惜当时没学会,再次接触二分法确实有点不会,不过理顺思路还是不难的。
#include<iostream> #include<stdio.h> #include<fstream> double ans(double x) { return 8 * x*x*x*x + 7 * x*x*x + 2 * x*x + 3 * x + 6; } using namespace std; int main() { //ifstream cin("in.txt"); int T; double y = 0; cin >> T; while(T--) { cin >> y; if (ans(0) > y || ans(100) < y) { cout << "No solution!" << endl; continue; } double low = 0, high = 100; while (high - low > 1e-10) { double mid = (high + low) / 2; if (ans(mid) > y) high = mid; else low = mid; } printf("%.4lf\n", (low + high) / 2); } return 0; }