迭代算法(七)

Posted on 2018-10-26 10:34  时光top  阅读(373)  评论(0编辑  收藏  举报

一·迭代算法的思想

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

二·实例演练

  `求平方根`问题

  代码实现:

#include "stdio.h"
#include "math.h"
int main()
{
    double a, x0, x1;
    printf("Input a:\n");
    scanf("%lf", &a);
    if (a<0)
    {
        printf("Error!\n");
    }
    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:\n");
    printf("sqrt(%g)=%g\n", a, x1);
    system("pause");
    return 0;
}
 

  实现结果:

三·总结

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

  

  

Copyright © 2024 时光top
Powered by .NET 8.0 on Kubernetes