## 算法第二章实践报告

#include<iostream>

#include<iomanip>

using namespace std;

double f(double x)

{

return x*x*x*x*x-15*x*x*x*x+85*x*x*x-225*x*x+274*x-121;

}

int main()

{

double left=1.5,right=2.4;

double mid;

while(right-left>1e-7)

{

mid=(left+right)/2.0;

if(f(mid)>=0.0){

left=mid;

}

else

{

right=mid;

}

}

cout << fixed << setprecision(6) << mid<< endl;

return 0;

}

#include <iostream>

#include <iomanip>

#include <cmath>

using namespace std;

bool check(double mid)

{

double f = pow(mid,5)-15.0*pow(mid,4)+85.0*pow(mid,3)-225.0*pow(mid,2)+274.0*mid-121.0;

if(f > 0.0) return 1;

return 0;

}

int main()

{

double l=1.5, r=2.4, mid;

while(r-l > 0.00000001){

mid = (l+r)/2.0;

if (check(mid)) l = mid;

else r = mid;

}

cout << fixed << setprecision(6) << mid << endl;

return 0;

}

while(right-left>1e-7)

{

mid=(left+right)/2.0;

if(f(mid)>=0.0){

left=mid;

}

else

{

right=mid;

}

}

T=log0.0000001(2.4-1.5)=O(logn)

1．浮点数除法为得到精确结果应除以小数。例如：mid=(left+right)/2.0;

2．输出精确值需头文件#include<iomanip>和cout << fixed << setprecision()搭配

posted on 2021-10-05 20:08  lyxnov  阅读(107)  评论(0编辑  收藏  举报