本文实例为大家分享了C++实现二分法求连续一元函数根的具体代码,供大家参考,具体内容如下
设计一个用二分法求连续一元函数根的通用函数solve
此函数有三个参数:
函数的返回值为求得的解
要求编写main函数如下:
double fun(double x)
{
double y;
y=4*pow(x,3)-6*pow(x,2)+3*x-2;
return y;
}
int main()
{
cout<<"4*x^3-6*x^2+3*x-2=0在区间(1,2)的根为 x="<<solve(fun,1,2);
return 0;
}
C++实现:
#include <iostream>
#include <cmath>
using namespace std;
double solve(double (*fun)(double x), double a, double b);
double fun(double x);
int main() {
cout << "4*x^3-6*x^2+3*x-2=0在区间(1,2)的根为 x=" << solve(fun, 1, 2);
return 0;
}
double solve(double (*fun)(double x), double a, double b) {
double i = b - a;
double c = (a + b) / 2;
while (i > 0.0000001) {
i = b - a;
if (fun(c) == 0)return c;
if (fun(c) * fun(a) < 0) {
b = c;
c = (a + b) / 2;
} else {
a = c;
c = (a + b) / 2;
}
}
return c;
}
double fun(double x) {
double y;
y = 4 * pow(x, 3) - 6 * pow(x, 2) + 3 * x - 2;
return y;
}
总结:
函数与指针的结合 注意返回的类型与要求