Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在java中1的平方根等于1会返回false?_Java_Stream_Square Root - Fatal编程技术网

为什么在java中1的平方根等于1会返回false?

为什么在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

当我输入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,所以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);
}