Java sqrt() 方法及示例
java.lang.Math.sqrt(double a) 返回雙精度值的正確舍入正平方根。特殊情況 -
如果自變數為 NaN 或小於零,則結果為 NaN。
如果自變數為正無窮大,則結果為正無窮大。
如果自變數為正零或負零,則結果與自變數相同。
以下是 Java 中 Math 類 sqrt() 方法的實現示例 -
示例
import java.lang.*;
public class Demo {
public static void main(String[] args) {
// get two double numbers numbers
double x = 9;
double y = 25;
// print the square root of these doubles
System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));
}
}輸出
Math.sqrt(9.0)=3.0 Math.sqrt(25.0)=5.0
示例
現在我們來看另一個使用負值和其他值實現 sqrt() 方法的示例 -
import java.lang.*;
public class Demo {
public static void main(String[] args) {
// get two double numbers numbers
double x = -20.0;
double y = 0.0;
// print the square root of these doubles
System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));
}
}輸出
Math.sqrt(-20.0)=NaN Math.sqrt(0.0)=0.0
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP