使用 Java 中的 Math.sqrt 計算數字的平方根


為了在 Java 中獲取數字的平方根,我們使用 java.lang.Math.pow() 方法。 Math.pow(double a) 方法接受一個 double 資料型別的引數,並返回一個值,該值為引數的平方根。

宣告 − java.lang.Math.sqrt() 方法的宣告如下 −

public static double sqrt(double a)

其中 a 是我們希望找到平方根的數字。

讓我們看一個程式,在該程式中,我們使用 Math.sqrt() 方法查詢數字的平方根。

例子

 線上演示

import java.lang.Math;
public class Example {
   public static void main(String[] args) {
      // declaring and initializing some double values
      double x = 25;
      double y = 81;
      // computing the square roots
      System.out.println("The square root of "+ x + " is "+ Math.sqrt(x));
      System.out.println("The square root of "+ y + " is "+ Math.sqrt(y));
   }
}

輸出

The square root of 25.0 is 5.0
The square root of 81.0 is 9.0

更新日期: 26-Jun-2020

1K+ 檢視

開啟您的職業

完成課程獲得認證

開始
廣告
© . All rights reserved.