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 : の働きを示すため java.lang.Math.sqrt() 引数が NaN または +infinity の場合のメソッド。




// 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