1 条题解

  • 0
    @ 2025-4-7 21:28:47

    C :

    #include<stdio.h>
    #include<math.h>
    int main(){
    float a,x1,x2;
    scanf("%f",&a);
    x2=a;
      while(fabs(x1-x2)>1e-5){
      x1=x2;
      x2=(x1+a/x1)/2.0;
      }
    printf("%.4f\n",x1);
    return 0;
    }
    

    C++ :

    #include <stdio.h>
    #include <math.h>
    int main() {
    	float a, x, newx;
    	scanf("%f", &a);
    	newx = a;
    	do {
    		x = newx;
    		newx = 0.5 * (x + a / x);
    	} while (fabs(x - newx) >= 1e-5);
    	printf("%.4f\n", x);
    	return 0;
    }
    
    

    Pascal :

    var
      n:longint;
    begin
      readln(n);
      writeln(sqrt(n):0:4);
    end.
    

    Java :

    import java.util.*;
    public class Main {
        public static void main(String args[]) {
            Scanner cin=new Scanner(System.in);
            int a=cin.nextInt();
            double x;
            x=a/2;
            while(Math.abs(x-(x+a/x)/2)>0.00001)
                x=(x+a/x)/2;
            System.out.printf("%.4f\n", x);
        }
    }
    

    Python :

    def f(a, x):
        y = (x + a / x) / 2.0
        return y if 10**-5 > y - x > -10**-5 else f(a, y)
    print "%.4f" % (f(input(), 1))
    
    • 1

    信息

    ID
    1284
    时间
    1000ms
    内存
    32MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者