二分H2的位置,判断条件为是否有Hi < 0
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath> using namespace std; const double eps = 1e-; int N;
double A; int dcmp( double a )
{
if ( fabs(a) < eps ) return ;
return a < ? - : ;
} bool cal( double mid, double &ans )
{
double Hi2 = A, Hi1 = mid, Hi0;
for ( int i = ; i < N - ; ++i )
{
Hi0 = 2.0 * ( Hi1 + 1.0 ) - Hi2;
if ( dcmp( Hi0 ) < ) return false;
Hi2 = Hi1, Hi1 = Hi0;
}
ans = Hi0;
return true;
} int main()
{
while ( ~scanf( "%d%lf", &N, &A ) )
{
double l = 0.0, r = A;
//int cnt = 0;
double ans;
while ( dcmp( r - l ) > )
{
//++cnt;
double mid = ( l + r ) / 2.0;
//printf( "%f %f %f\n", l, r, mid );
double tmp;
if ( !cal( mid, tmp ) ) l = mid;
else
{
r = mid;
ans = tmp;
}
//if ( cnt > 100 ) break;
}
printf( "%.2f\n", ans );
}
return ;
}