我想制作一個與這個問題相關的程式:
可以表示為另一個整數平方的整數稱為完全平方,例如 4、9、16、25 等。撰寫一個程式來檢查一個數是否是完全平方。
我確實建立了類似的東西:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a ){ }
if (a*a == num){
System.out.println("Ok");
break;
}
else if (a*a != num){
System.out.println("Not ok");
}
}
}
所以當我運行它時它并沒有給出我想要的東西。我應該更改或添加什么?
uj5u.com熱心網友回復:
我認為您的 for 回圈解釋可能是錯誤的,我編造了一些可能會起作用的東西。試試這個代碼。如果你愿意,你也可以讓這個方法回傳一個布林值。
static void perfectSquare(int number) {
for (int i = 1; i < i * number; i) {
// 'i' is the divisor, making sure
// it is equal to the quotient
if ((number % i == 0) && (number / i == i)) {
System.out.println(i);
}
}
uj5u.com熱心網友回復:
如果你想暴力破解每個數字,那么你就在正確的軌道上,但如果回圈中的所有數字都失敗了,你應該只列印“Not ok”,否則你可能有一個完美的正方形,但“Ok”將隱藏在許多“Not好的”行。您的 for 回圈中也沒有任何內容,因此 if 陳述句始終檢查是否 0*0 == num。
這看起來可能是一個家庭作業問題,所以我不會為您提供完整的答案,但請考慮如何提高效率。
如果你找到了一個匹配的整數,你需要繼續嗎?
你需要檢查每個數字嗎?(起點可能是遵循二分搜索的原則)
uj5u.com熱心網友回復:
我最終是這樣的:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
int b = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a ){
if (a*a == num){
b = 1;
break;
}
}
if(b==1){
System.out.println("Perfect Square");
}
else {
System.out.println("Not ok");
}
}
}
謝謝你的支持 !
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/522321.html
標籤:爪哇