1 solutions

  • 0
    @ 2025-11-5 19:53:42

    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
    
    
    • 1

    Information

    ID
    19795
    Time
    1000ms
    Memory
    32MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By