當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java sqrt()用法及代碼示例


java.lang.Math.sqrt()返回作為參數傳遞給它的double類型值的平方根。如果參數為NaN或負數,則結果為NaN。如果參數為正無窮大,則結果為正無窮大。如果傳遞的參數為正零或負零,則結果將與參數相同。

用法

public static double sqrt(double a)
Parameter:
a:the value whose square root is to be returned.
Return:
This method returns the positive square root value of 
the argument passed to it.

例子1:顯示java.lang.Math.sqrt()方法的用法。

// Java program to demonstrate working 
// of java.lang.Math.sqrt() method 
import java.lang.Math; 
  
class Gfg { 
  
    // driver code 
    public static void main(String args[]) 
    { 
        double a = 30; 
  
        System.out.println(Math.sqrt(a)); 
  
        a = 45; 
  
        System.out.println(Math.sqrt(a)); 
  
        a = 60; 
  
        System.out.println(Math.sqrt(a)); 
  
        a = 90; 
  
        System.out.println(Math.sqrt(a)); 
    } 
}

輸出:

5.477225575051661
6.708203932499369
7.745966692414834
9.486832980505138

例子2:當參數為NaN或+ infinity時,顯示java.lang.Math.sqrt()方法的用法。

// Java program to demonstrate working 
// of java.lang.Math.sqrt() method 
import java.lang.Math; // importing java.lang package 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        double positiveInfinity = Double.POSITIVE_INFINITY; 
        double negativeVal = -5; 
        double nan = Double.NaN; 
        double result; 
  
        // Here argument is negative, 
        // output will be NaN 
        result = Math.sqrt(negativeVal); 
        System.out.println(result); 
  
        // Here argument is positive infinity, 
        // output will also positive infinity 
        result = Math.sqrt(positiveInfinity); 
        System.out.println(result); 
  
        // Here argument is NaN, output will be NaN 
        result = Math.sqrt(nan); 
        System.out.println(result); 
    } 
}

輸出:

NaN
Infinity
NaN




相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 Java sqrt() method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。