hdu 2199 Can you solve this equation?

求导后发现,f ‘ 恒大于0,用二分法求即可,剪除条件:f(100)<y || f(0)>y。最后输出mid,结果WA,改为输出(left+right)/2通过。后来明白:当left=right时会跳出循环,而mid是不正确的。

 

#include<stdio.h>
#include<math.h>

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

int main()
{
	int t;
	double y,left,right,mid;
	scanf("%d",&t);
	while(t--){
		scanf("%lf",&y);
		if(cal(100)<y||cal(0)>y){
			printf("No solution!\n");
			continue;
		}
		left=0;
		right=100;
		while(right-left>1e-6){
			mid=(left+right)/2;
			double ans=cal(mid);
			if(ans<y){
				left=mid+1e-6;
			}
			if(ans>y){
				right=mid-1e-6;
			}
		}
		printf("%.4lf\n",(left+right)/2);
		


	}


	return 0;
}

你可能感兴趣的:(hdu 2199 Can you solve this equation?)