使用 C++ 中的割线法查找方程根程序


本教程中,我们将学习一个使用割线法查找方程根的程序。

为此,我们将有一个方程提供给我们。我们的任务是使用迭代割线法找出该方程的根。

示例

 演示

#include <bits/stdc++.h>
using namespace std;
float f(float x) {
   float f = pow(x, 3) + x - 1;
   return f;
}
void secant(float x1, float x2, float E) {
   float n = 0, xm, x0, c;
   if (f(x1) * f(x2) < 0) {
      do {
         //calculating the intermediate value
         x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
         c = f(x1) * f(x0);
         x1 = x2;
         x2 = x0;
         n++;
         if (c == 0)
         break;
         xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
      } while (fabs(xm - x0) >= E);
      cout << "Root of the given equation=" << x0 << endl;
      cout << "No. of iterations = " << n << endl;
   } else
   cout << "Can not find a root in the given inteval";
}
int main() {
   // initializing the values
   float x1 = 0, x2 = 1, E = 0.0001;
   secant(x1, x2, E);
   return 0;
}

输出

Root of the given equation=0.682326
No. of iterations = 5

更新时间:19-May-2020

963 次浏览

开启你的 职业 生涯

完成课程获得认证

开始
广告
© . All rights reserved.