在这里,我们将解释如何在Java中编写一个程序来检查一个数是否是完全平方根。
我们可以使用函数Math.sqrt()来找到一个数的平方根。Math.sqrt()函数的语法如下所示。
public static double sqrt(double x)
首先,我们必须声明类Square。然后声明整数变量num。创建一个扫描器类的对象为sc。从用户那里读取数字到变量num中。检查isPS(num)是返回true还是false。如果返回true,则将该数字显示为完全平方数。否则,显示该数字不是完全平方数。
如果数字是完全平方数,则isPs(x)函数将返回true。要找出数字的平方根,我们可以使用函数Math.sqrt()。然后我们将使用Math.floor()函数找出数字的最近整数。然后我们将找出sr和Math.floor(sr)之间的差值。如果差值等于零,则返回true。
步骤1:声明带有public修饰符的类Square。
步骤 2:打开**main()**函数以启动程序,Java程序的执行从**main()**开始
步骤3:声明整数变量num。
步骤4:检查isPS(num),如果为true,则将该数字显示为完全平方数。
步骤5:否则,显示该数字不是完全平方数。
函数 static boolean isPS(double x)
步骤1:通过调用函数Math.sqrt(x)将x的平方根存储到变量sr中。
步骤2:检查sr - Math.floor(sr)是否等于零,如果是则返回true。
import java.util.Scanner;
public class Square {
static boolean isPS(double x) {
double sr = Math.sqrt(x);
return ((sr - Math.floor(sr)) == 0);
}
public static void main(String[] args) {
int num;
Scanner sc = new Scanner(System. in );
System.out.println("Enter the Number: ");
num = sc.nextInt();
if (isPS(num)) System.out.println("The Number " + num + " is a perfect square");
else System.out.println("The Number " + num + " is not a perfect square");
}
}
Enter the Number: 25 The Number 25 is a perfect square