我想寫一個循環,調用一個方法來確定輸入的數字是否是一個完美的正方形。它編譯得很好,所以我必須有一個邏輯錯誤,對於我來說,儘管我找不到它。不管我輸入的數字是什麼,它總是返回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