📄 rootbise.cpp
字号:
///////////////////////////////////////////////////
// §5 方程求根
//
// 程序5.1 二分法求方程根
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include "expressi.cpp"
#define PRECISION 0.000001
// 二分求根, f(x) = FxString, 区间[a,b]
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -