我想写一个循环,调用一个方法来确定输入的数字是否是一个完美的正方形。它编译得很好,所以我必须有一个逻辑错误,对于我来说,尽管我找不到它。不管我输入的数字是什么,它总是返回false,导致我相信问题出在isPerfect()方法中。然而,我对java还不够了解,但还不知道该从哪里出发。这里是我到目前为止的代码:找到完美的正方形
public class Square
{
public static void main(String[] args)
{
int input = 0; //The default value for input
Scanner keyboard = new Scanner(System.in);
while (input != -1)
{
System.out.println("Please enter a number, or enter -1 to quit");
input = keyboard.nextInt();
if (isPerfect(input) == true) //Call isPerfect() to determine if is a perfect square
{
System.out.println(input + " is a perfect square.");
}
else if(input == -1) //If equals exit code, quit
{
break;
}
else //If it is not a perfect square... it's not a perfect square
{
System.out.println(input + " is not a perfect square.");
}
}
}
public static boolean isPerfect(int input)
{
double num = Math.sqrt(input); //Take the square root of the number passed
if (((num * num) == input) && (num%1 == 1)) //If the number passed = it's roots AND has no remainder, it must be a perfect sqaure
{
return true; //Return true to the call
}
else
{
return false; //Return false to the call
}
}
}
尝试#1时,我得到一个转换错误,尽管第二号似乎已经奏效。现在我发现它让我有更多的理解,然后我尝试了一些令人费解的巫术。 'code:'Square.java:47:error:incompatible types:possible lossy conversion from double to int'' – brodieR
I fixed it,changed to int num =((int)Math.sqrt(input)); – brodieR