Java中带有示例的Math pow()方法用法

2021年4月20日14:43:45 发表评论 912 次浏览

java.lang.Math.pow()用于计算一个加到其他数的幂的数。此函数接受两个参数, 并将第一个参数的值返回到第二个参数。下面列出了一些特殊情况:

  • 如果第二个参数为正或负零, 则结果将为1.0。
  • 如果第二个参数是1.0, 则结果将与第一个参数的结果相同。
  • 如果第二个参数是NaN, 那么结果也将是NaN。

语法:

public static double pow(double a, double b)
Parameter:
a : this parameter is the base
b : this parameter is the exponent.
Return :
This method returns ab.

例子1:显示工作原理java.lang.Math.pow()方法。

//Java program to demonstrate working
//of java.lang.Math.pow() method
  
import java.lang.Math;
  
class Gfg {
  
     //driver code
     public static void main(String args[])
     {
         double a = 30 ;
         double b = 2 ;
         System.out.println(Math.pow(a, b));
  
         a = 3 ;
         b = 4 ;
         System.out.println(Math.pow(a, b));
  
         a = 2 ;
         b = 6 ;
         System.out.println(Math.pow(a, b));
     }
}

输出如下:

900.0
81.0
64.0

例子2:显示工作原理java.lang.Math.pow()当参数为NaN时的方法。

//Java program to demonstrate working
//of java.lang.Math.pow() method
import java.lang.Math; //importing java.lang package
  
public class GFG {
     public static void main(String[] args)
     {
  
         double nan = Double.NaN;
         double result;
  
         //Here second argument is NaN, //output will be NaN
         result = Math.pow( 2 , nan);
         System.out.println(result);
  
         //Here second argument is zero
         result = Math.pow( 1254 , 0 );
         System.out.println(result);
  
         //Here second argument is one
         result = Math.pow( 5 , 1 );
         System.out.println(result);
     }
}

输出如下:

NaN
1.0
5.0

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: