迭代算法(七)

一·迭代算法的思想

  迭代算法在使用过程需要做好如下3方面的工作:(1)确定迭代变量(2)建立迭代关系(3)对迭代过程的控制

二·实例演练

  `求平方根`问题

  代码实现:

#include "stdio.h"
#include "math.h"
int main()
{
    double a, x0, x1;
    printf("Input a:
");
    scanf("%lf", &a);
    if (a<0)
    {
        printf("Error!
");
    }
    else
    {
        x0 = a / 2;
        x1 = (x0 + a / x0) / 2;
        do 
        {
            x0 = x1;
            x1 = (x0 + a / x0) / 2;
        } while (fabs(x0-x1)>pow(10,-6));
    }
    printf("Result:
");
    printf("sqrt(%g)=%g
", a, x1);
    system("pause");
    return 0;
}
 

  实现结果:

三·总结

  递归是自顶向下运算,是在函数内部调用自身,而迭代是循环求值。

  

  

原文地址:https://www.cnblogs.com/hxf175336/p/9854945.html