温馨提示×

c语言如何求方程的根

小亿
94
2024-08-01 17:07:15
栏目: 编程语言

在C语言中,可以使用数值计算方法来求解方程的根。其中,最常用的方法包括牛顿迭代法、二分法等。以下是一个使用牛顿迭代法求解方程根的示例代码:

#include <stdio.h>
#include <math.h>

double func(double x) {
    return x * x - 4; // 要求解的方程为 x^2 - 4 = 0
}

double derivative(double x) {
    return 2 * x; // 方程的导数为 2 * x
}

double newtonRaphson(double x) {
    double h = func(x) / derivative(x);
    while (fabs(h) >= 0.0001) {
        h = func(x) / derivative(x);
        x = x - h;
    }
    return x;
}

int main() {
    double x0 = 1; // 初始猜测值
    double root = newtonRaphson(x0);
    printf("方程的根为:%f\n", root);
    return 0;
}

在上面的代码中,首先定义了要求解的方程和其导数的函数funcderivative,然后使用牛顿迭代法newtonRaphson来不断逼近方程的根。最后,通过给定的初始猜测值,求解出了方程的根并输出结果。

0