迭代求立方根

题目描述:

立方根的逼近迭代方程是 y(n+1) = y(n)*2/3 + x/(3*y(n)*y(n)),其中y0=x.求给定的x经过n次迭代后立方根的值。

输入:

输入有多组数据。
每组一行,输入x n。

输出:

迭代n次后的立方根,double精度,保留小数点后面六位。

样例输入:

4654684 1
65461 23

样例输出:

3103122.666667
40.302088

链接:

http://codeup.cn/problem.php?cid=100000588&pid=10

思路:有两种方法,一种是递归,一种是迭代

1.递归

#include<iostream>
#include<iomanip>
using namespace std;
double y(double x,int n){
    double ans;
    if(n==0){
        ans=1.0*x;
        return ans;
    }
    else{
        ans=y(x,n-1)*2/3+x/(3*y(x,n-1)*y(x,n-1));
        return ans;
    }
}

int main(){
    double x;
    int n;
    while(cin>>x>>n){
        cout<<fixed<<setprecision(6)<<y(x,n)<<endl;
    }
    return 0;
}

2.迭代

#include <stdio.h>
int main(){
    int x, n;
    while(scanf("%d%d", &x, &n) != EOF){
    double sum = x;
    for(int i = 0; i < n; i++)
        sum = sum * 2 / 3 + x / ( 3 * sum * sum);
    printf("%.6f
", sum);
    }
    return 0;
}

原文地址:https://www.cnblogs.com/ak918xp/p/13522433.html