Java 常见例子

如果一个数字与其自身相乘 (n*n),则最终数字将是该数字的平方,并且求数字的平方根是倒数数的平方运算。如果xy的平方根,则可以表示为:

Java 数字的平方根

或者,也可以表示为:

x2 = y

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

sqrt() 方法可用于返回数字的平方根。

import java.lang.Math;

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

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

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

Square root of 16.0 is 4.0
Square 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 = 16;
	double y = 25;
	
	//pow() 以 double 数据类型作为参数
	double x1 = Math.pow(x, 0.5);
	double y1 = Math.pow(y, 0.5);
	System.out.println("Square root of " + x + " is " + x1);
	System.out.println("Square root of " + y + " is " + y1);
  }
} 

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

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0