rootbise.cpp

来自「从出版社求得的经典数值算法」· C++ 代码 · 共 50 行

CPP
50
字号
///////////////////////////////////////////////////
//	§5  方程求根
//
//	程序5.1 二分法求方程根


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

#include "expressi.cpp"

#define PRECISION	0.000001


float RootByBisection(char FxString[],float a,float b)
{
	float x1,x2;

	if(CreateFx(FxString)) return(0.0);
	x1=a;
	x2=b;

	while(fabs(x2-x1)>PRECISION)
		if(f(x1)*f((x1+x2)/2)<0)
			x2=(x1+x2)/2;
		else
			x1=(x1+x2)/2;

	return(x1);
}

void main()
{
	float x1,x2;
	char FxString[200];

	printf("\nInput function with varable x,x1,x2 : ");
	scanf("%s %f %f",FxString,&x1,&x2);
	printf("\nRoot x=%f",RootByBisection(FxString,x1,x2));
}

/*
	运行实例:

Input function with varable x,x1,x2 : pow(x,3)-x-1 1 2

Root x=1.324718
*/

⌨️ 快捷键说明

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