1.二分法:
#include <stdio.h>
// 定义函数指针
typedef double (*Function)(double);
inline double f(double x) {
return x * x - 2;
}
inline double bisection(double a, double b, double threshold, int maxIterations, Function f) {
double fa = f(a);
double fb = f(b);
if (fa * fb > 0) {
return 0;
}
int i = 0;
while (b - a >= threshold && i < maxIterations) {
double c = a + (b - a) / 2;
double fc = f(c);
if (fa * fc < 0) {
b = c;
}
else {
a = c;
fa = fc;
}
i++;
}
return (a + b) / 2;
}
int main() {
double x = bisection(1, 2, 0.00001, 100, f);
if (x == 0) {
printf("无解或无法求解\n");
}
else {
printf("方程的解为:%f\n", x);
}
return 0;
}
2.牛顿迭代法: