Java 常见例子

如果一个数字与其本身相乘两次 (n*n*n),则最终数字将是该数字的立方并找到以下立方根数字是数字的立方的逆运算。如果xy的立方根,则可以表示为:

Java 数字的立方根

或者,也可以表示为:

x3 = y

方法一:使用Java数学类的cbrt()方法

cbrt() 方法可用于返回数字的立方根。

import java.lang.Math;

public class MyClass {
  public static void main(String[] args) {
		double x = 64;
		double y = 125;

		//cbrt() 采用双精度数据类型作为参数
		double x1 = Math.cbrt(x);
		double y1 = Math.cbrt(y);
		System.out.println("Cube root of " + x + " is " + x1);
		System.out.println("Cube root of " + y + " is " + y1);
  }
} 

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

Cube root of 16.0 is 4.0
Cube root of 25.0 is 5.0 

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

Java Math类的pow()方法也可以用来计算数字的立方根。

import java.lang.Math;

public class MyClass {
  public static void main(String[] args) {
		double x = 64;
		double y = 125;
		
		//pow() 以 double 数据类型作为参数
		double x1 = Math.pow(x, 1/3.);
		double y1 = Math.pow(y, 1/3.);
		System.out.println("Cube root of " + x + " is " + x1);
		System.out.println("Cube root of " + y + " is " + y1);
  }
} 

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

Cube root of 64.0 is 3.9999999999999996
Cube root of 125.0 is 4.999999999999999