public static boolean checkSquare(int i){
return IntStream
.rangeClosed(1, i/2)
.anyMatch(x -> Math.sqrt(x) == i);
}
当我输入 1 作为用户输入时,它返回 false。我不明白为什么 1 的平方根不等于 1。谁能告诉我我的代码是否正确?
public static boolean checkSquare(int i){
return IntStream
.rangeClosed(1, i/2)
.anyMatch(x -> Math.sqrt(x) == i);
}
当我输入 1 作为用户输入时,它返回 false。我不明白为什么 1 的平方根不等于 1。谁能告诉我我的代码是否正确?
如果您的用户输入被分配了您的i
变量,那么很清楚为什么
IntStream.rangeClosed(1, i/2).anyMatch(x -> Math.sqrt(x) == i);
返回false
时i==1
,因为1/2 == 0
,所以IntStream.rangeClosed(1, 0)
是一个空流。
将您的方法更改为:
public static boolean checkSquare(int i){
return IntStream
.rangeClosed(1, i)
.anyMatch(x -> Math.sqrt(x) == i);
}
或者,如果您真的想保持将大小减半的优化IntStream
:
public static boolean checkSquare(int i) {
return IntStream
.rangeClosed(1, Math.max(1,i/2))
.anyMatch(x -> Math.sqrt(x) == i);
}