Java 常见例子

如果数字的幂(或指数)表示该数字与其自身相乘以获得最终数字。例如:

x2 次幂 = x² = x*x

x3 次幂 = x³ = x*x*x

方法 1:使用条件语句

在下面的示例中,创建了一个名为Power()的方法来计算数字的幂。它使用while循环来实现这一点。此方法可用于计算数字的幂,其中幂应为非负整数。

public class MyClass {
  static void Power(double x, int n) {
    double finalnum = 1;
    int n1 = n;
    while(n1 > 0){
      finalnum = finalnum * x;
      n1--;
    }
    System.out.println(x + " raised to the power " + n + " = " + finalnum);
  }

  public static void main(String[] args) {
    Power(3, 5);
    Power(5, 0);
    Power(6, 2);
  }
} 

上面的代码将给出以下输出:

3.0 raised to the power 5 = 243.0
5.0 raised to the power 0 = 1.0
6.0 raised to the power 2 = 36.0 

方法二:使用Java Math类的pow()方法

Java Math类的pow()方法也可以用来计算幂数字。它可用于计算任何 n 值的 xn(n 可以是负数或分数)。

import java.lang.Math;

public class MyClass {
  public static void main(String[] args) {
    double x = 3, y = 5, z = 6;
    double a = 5, b = 0, c = 2;

    System.out.println(x + " raised to the power " + a + " = " + Math.pow(x, a));
    System.out.println(y + " raised to the power " + b + " = " + Math.pow(y, b));
    System.out.println(z + " raised to the power " + c + " = " + Math.pow(z, c));
  }
} 

上面的代码将给出以下输出:

3.0 raised to the power 5.0 = 243.0
5.0 raised to the power 0.0 = 1.0
6.0 raised to the power 2.0 = 36.0