码迷,mamicode.com
首页 > 其他好文 > 详细

(hdu step 4.1.1)Can you solve this equation?(使用二分法来求解方程组的解)

时间:2015-02-16 14:21:28      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Can you solve this equation?

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 915 Accepted Submission(s): 436
 
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;
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
 
 
Recommend
lcy


题目分析:

               简单题。是用二分法来求方程组的解。使用二分法来求方程组的解的前提是该方程具有单调性。


代码如下:

/*
 * a.cpp
 *
 *  Created on: 2015年2月16日
 *      Author: Administrator
 */

#include <iostream>
#include <cstdio>
#include <cmath>



using namespace std;

const double delta = 1e-6;//1e10表示10^10

double function(double x){
	return 8*pow(x,4.0) + 7*pow(x,3) + 2*pow(x,2) + 3*x + 6;
}



/**
 * 用二分法来求解方程组的解
 * y:方程组右边的数
 */
double work(double y){
	double mid;
	double left = 0;
	double right = 100;

	while(right - left > delta){//如果右边的索引还比左边的索引大
		mid = (left+right)/2;//计算中间值

		if(function(mid) < y){//如果y大于中间值...注意这种写法
			left = mid+(1e-7);//移动左边的索引。需要注意的是这里使用的偏移量应该比上面的小
		}else{//否则
			right = mid-(1e-7);//移动右边的索引
		}
	}

	return (left+right)/2;//返回最后的值
}




int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		double y;
//		scanf("%d",&y);

		cin >> y;

		if(function(0) <= y && y <= function(100)){
			printf("%.4lf\n",work(y));
//			printf("%.4lf\n",find(y));
		}else{
			printf("No solution!\n");
		}
	}

	return 0;
}








(hdu step 4.1.1)Can you solve this equation?(使用二分法来求解方程组的解)

标签:

原文地址:http://blog.csdn.net/hjd_love_zzt/article/details/43851437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!