HDU 2199 Can you solve this equation? 二分查找

HDU 2199 Can you solve this equation?

Problem Description

Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solution between 0 and 100;
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!

Author

Redow



简要题意

给出一个实数Y, 判断0到100之间是否存在一个实数X, 使得X与Y之间满足 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y 这个方程, 结果保留四位小数

分析

很简单的一道实数二分模板题, 但是做了很久, 甚至照着网上的代码改了好久都没过, 最后用自己原来的代码把cin改成scanf就过了, 很神秘

代码实现_1

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;

int t;
double n;

bool check(double x)
{
	if (8*pow(x,4) + 7*pow(x,3) + 2*pow(x,2) + 3*x + 6 > n)
		return false;
	else	return true;
}

double b_search(double x)
{
	double l = 0, r = 100;
	while (r - l >= 1e-8)
	{
		double mid = (l + r) / 2;
		if (check(mid))	l = mid;
		else	r = mid;
	}
	return (l+r)/2;
}

int main(void)
{
	ios::sync_with_stdio(false);
	cin >> t;
	while (t --)
	{
		scanf("%lf", &n);
		if (n < 6 || check(100))	cout << "No solution!" << endl;
		else
		{
			double x = b_search(n);
			printf("%.4lf\n", x);
		}
	}
	return 0;
}

这是最后改过的代码, 一开始写的代码只是中间的scanf("%lf", &n);换成cin>>n;, 因为这么一个小问题改了一个多小时, 我恨啊!!!

另外, 自己写的这个代码思维有些局限, 比如check()函数的实现, 略显麻烦, 于是参考了网上的代码后有了如下改进后的代码:

代码实现_2

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;

int t;
double n;

double func(double x)
{
	return 8*x*x*x*x + 7*x*x*x + 2*x*x + 3*x + 6;
}

double b_search(double n)
{
	double l = 0, r = 100;
	double mid;
	while (r - l > 1e-7)
	{
		mid = (l + r) / 2;
		if (func(mid) == n)	return mid;
		else if (func(mid) > n)	r = mid;
		else	l = mid;
	}
	return (l + r) / 2;
}

int main(void)
{
	ios::sync_with_stdio(false);
	cin >> t;
	while (t --)
	{
		scanf("%lf", &n);
		if (n < 6)
		{
			cout << "No solution!" << endl;
			continue;
		}
		else if (n > 8*pow(100,4) + 7*pow(100,3) + 2*pow(100,2) + 3*100 + 6)
		{
			cout << "No solution!" << endl;
			continue;
		}
		else
		{
			printf("%.4lf\n", b_search(n));
		}
	}
	return 0;
}

收获与反思

  1. 之后的实数二分, 为了保证精度, 均使用scanf读入实数
  2. 之前考虑过是否是pow()函数导致的精度问题, 但是发现跟它没啥关系
  3. 题目要求保留4位小数, 还是额外多3位小数比较保险
  4. 函数可以只是把一个复杂的表达式帮我们写出来, 可以不在函数内部进行判断, 这样该函数的泛用性会更大
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值