luanpaixie262 于 2016.03.17 09:08 提问

java判断完全平方数⋯⋯⋯⋯⋯⋯

3个回答

u011489205   2016.03.17 10:14

`````` public static boolean isSquares(int value) {
if (value < 0) {
return false;
}
double sqrtValue = Math.sqrt(value * 1.0);
int sqrtSimiValue = (int) sqrtValue;
if ((sqrtSimiValue * sqrtSimiValue) == value) {
return true;
} else {
return false;
}
}

public static boolean isSquares2(int value) {
if (value < 0) {
return false;
}

int item = value / 2;
for (int index = item; index >= 0; index--) {
if (index * index == value) {
return true;
}
}
return false;

}
``````
luanpaixie262 回复SionTiger: 如何当输入-1结束呢

hgq0916   2016.03.21 23:17

u011489205   2016.03.17 16:25

``````public class Squares{
public static void main(String[] args) {

try {
boolean first = true;
int[] inputs = new int[1024];
int index = 0;
int value = 0;
while(true){
if(first){
System.out.print("请输入一组数，输入-1结束输入：");
first = false;
} else {
System.out.print("请输入下一组数，输入-1结束输入：");
}

str = str.trim();
value = Integer.valueOf(str);
if(value == -1){
break;
}
inputs[index++] = value;
}

for(int i=0; i < index; i++ ){
System.out.println(isSquares(inputs[i]));
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static boolean isSquares(int value) {
if (value < 0) {
return false;
}
double sqrtValue = Math.sqrt(value * 1.0);
int sqrtSimiValue = (int) sqrtValue;
if ((sqrtSimiValue * sqrtSimiValue) == value) {
return true;
} else {
return false;
}
}

public static boolean isSquares2(int value) {
if (value < 0) {
return false;
}

int item = value / 2;
for (int index = item; index >= 0; index--) {
if (index * index == value) {
return true;
}
}
return false;

}
}
``````