为什么在java中1的平方根等于1会返回false?
当我输入1作为用户输入时,它返回false。我不明白为什么1的平方根不等于1。有人能告诉我我的代码是否正确吗?如果您的用户输入被分配了i变量,那么原因很清楚为什么在java中1的平方根等于1会返回false?,java,stream,square-root,Java,Stream,Square Root,当我输入1作为用户输入时,它返回false。我不明白为什么1的平方根不等于1。有人能告诉我我的代码是否正确吗?如果您的用户输入被分配了i变量,那么原因很清楚 public static boolean checkSquare(int i){ return IntStream .rangeClosed(1, i/2) .anyMatch(x -> Math.sqrt(x) == i); } 当i==1时返回false,因为1/2==0
public static boolean checkSquare(int i){
return IntStream
.rangeClosed(1, i/2)
.anyMatch(x -> Math.sqrt(x) == i);
}
当i==1时返回false,因为1/2==0,所以IntStream.rangeClosed1,0是空流
将您的方法更改为:
IntStream.rangeClosed(1, i/2).anyMatch(x -> Math.sqrt(x) == i);
或者,如果您确实希望保持将IntStream大小减半的优化:
进一步阅读:请不要把一个已经存在的问题完全换成别的问题。现在我明白我的错误了。非常感谢您的解释。@SendHelp如果一个答案确实解决了您的问题,请将其标记为答案。
public static boolean checkSquare(int i){
return IntStream
.rangeClosed(1, i)
.anyMatch(x -> Math.sqrt(x) == i);
}
public static boolean checkSquare(int i) {
return IntStream
.rangeClosed(1, Math.max(1,i/2))
.anyMatch(x -> Math.sqrt(x) == i);
}