⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bisection.cpp

📁 二分法求一个未知数方程的根f(x)=0,x属于[a,b],除了显示每次计算的小区间外
💻 CPP
字号:
////////////////
/////二分法求一个未知数方程的根f(x)=0,x属于[a,b]
/////改进:除了显示每次计算的小区间外,还根据给定的精度计算了所需的次数k
/////其中k>[log(b-a)-log(2*err)]/log(2);log=ln;
/////完善二分法的模块
////////////////
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
//////////
double fun(double x);
void RootByBisection(double(*pf)(double x));
//////////
//////////
int main()
{
	RootByBisection(fun);
	return 0;
}
//////////
//////////
double fun(double x)
{
	return (x*x*x-x-1);
}
//////////
void RootByBisection(double(*pf)(double x))
{
	double x1,x2,err;
	int flag;///记录迭代次数
	cout<<"请输入一元函数f(x)的定义域下界:a=";cin>>x1;
	cout<<"请输入一元函数f(x)的定义域上界:b=";cin>>x2;
	cout<<"请输入精度要求(推荐取err=1E-6):err=";cin>>err;
	flag=static_cast<int>((log(x2-x1)-log(2*err))/log(2))+2;
	cout<<"预估:需计算的次数大约为:"<<flag<<endl;
	cout.precision(10);
	cout<<endl<<"第0次的小区间为:"<<"["<<setw(12)<<x1
		<<","<<setw(12)<<x2<<"]"<<endl;
	flag=0;
	while(fabs(x2-x1)>err)
	{
		if(pf(x1)*pf((x1+x2)/2)<0)
			x2=(x1+x2)/2;
		else
			x1=(x1+x2)/2;
		flag=flag+1;
		cout<<"第"<<flag<<"次的小区间为:"<<"["<<setw(12)<<x1
		<<","<<setw(12)<<x2<<"]"<<endl;
	}
	cout<<endl<<"方程的近似根为:root="<<x1<<endl;
	cout<<"函数值f(root)="<<pf(x1)<<endl;
}
//////////
//////////

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -