初始根为[-2,0]用C++二分法求出一元非线性方程f(x)=x^3-sinx-4x+1的全部实根,精度为10^(-4),并输出每次运算的结果
时间: 2024-01-05 16:05:49 浏览: 101
C/C++语言的二分法求方程的根
5星 · 资源好评率100%
#include <stdio.h>
#include <math.h>
double f(double x) {
return x*x*x - sin(x) - 4*x;
}
int main() {
double a = -2, b = 0, c, fa, fb, fc;
int count = 0;
do {
c = (a+b)/2;
fa = f(a);
fb = f(b);
fc = f(c);
printf("a=%f, b=%f, c=%f, fa=%f, fb=%f, fc=%f\n", a, b, c, fa, fb, fc);
if (fc*fa < 0) {
b = c;
} else {
a = c;
}
count++;
} while (fabs(f(c)) >= 1e-4 && count < 100);
printf("The root is %f\n", c);
return 0;
}
阅读全文