使用c语言 编写一段程序求解f(x) = x^3 + x^2 - 1 = 0,使用二分法
时间: 2024-06-03 13:07:47 浏览: 165
#include <stdio.h>
#include <math.h>
double f(double x) {
return pow(x, 3) - pow(x, 2) - 1;
}
double bisection(double a, double b, double eps) {
double c;
while (fabs(b - a) > eps) {
c = (a + b) / 2.0;
if (f(c) == 0.0) return c;
else if (f(a) * f(c) < 0.0) b = c;
else a = c;
}
return (a + b) / 2.0;
}
int main() {
double a = -10.0, b = 10.0, eps = 0.00001;
double root = bisection(a, b, eps);
printf("Root of the equation is: %lf\n", root);
return 0;
}
相关问题
使用二分法,利用c语言 编写一段程序求解f(x) = x^3 + x^2 - 1 = 0
#include <stdio.h>
#include <math.h>
double f(double x) {
return pow(x, 3) - pow(x, 2) - 1;
}
int main() {
double a = 1, b = 2, c, eps = 1e-6;
while (b - a > eps) {
c = (a + b) / 2;
if (f(c) * f(a) < 0) {
b = c;
} else {
a = c;
}
}
printf("The root of the equation is: %lf\n", c);
return 0;
}
阅读全文