1594 - 迭代求立方根

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 32 MB


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

<br />

题目输入


输入有多组数据。<br />

每组一行,输入x n。

<br />

题目输出


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

<br />

输入/输出样例

输入格式

4654684 1
65461 23

输出格式

3103122.666667
40.302088

C语言解答

//立方根的逼近迭代方程是 y(n+1) = y(n)*2/3 + x/(3*y(n)*y(n)),其中y0=x.
#include<stdio.h>
#include<stdlib.h>
int main()
{
  double x,y;
  int n;
  while(scanf("%lf %d",&x,&n)!=EOF){
    y=x;
    while(n--){y=y*2/3+x/(3*y*y);}
    printf("%.6lf\n",y);
  }
}

C++解答

#include <iostream>
#include <cstdio>
using namespace std;

long long n;
double x,y;

int main(int argc,char* argv[]){
    while(cin>>x>>n){
        y = x;
        for(long long i=0;i<n;i++){
            y = y*2/3 + x/(3*y*y);
        }
        printf("%.6f\n",y);
    }
    return 0;
}

Java解答



import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
   private static Scanner s = new Scanner(System.in) ;
   private static DecimalFormat df = new DecimalFormat("0.000000") ;
   public static void main(String[] args) {
	  while(s.hasNext()){
	    long x = s.nextLong() ;
	    int n = s.nextInt() ;
	  
	    System.out.println(df.format(y(x, n)));
	  }
   }
   
   public static double y(long x , int n){
	   double result = x ;
	   while(n>0){
		  result =  result*2/3 + x/(3*result*result) ;
		   n-- ;
	   }
	   return result ;
   }
}

Python解答

# coding=utf-8
import sys
sys.setrecursionlimit(2000)

def y(x,n):
    if(x == 0):  return 0
    if(n == 0):  return x
    last = y(x,n-1)
    return last*(2/3) + x/(3*last**2)

try:
    while True:
        x, n = map(float, input().split())
        print("%.6lf"%y(x,n))
except Exception as e:
    #print(e)
    pass