简体   繁体   English

在假布尔值上使用not语句

[英]Using not statement on false boolean

I'm always assumed that if a statement was declared false, such as boolean valid = false , then writing !valid would in turn reverse valid to be true. 我一直认为,如果声明为false,例如boolean valid = false ,则编写!valid会反过来将valid反转为true。 Yet, was this an entirely wrong misconception? 但是,这是完全错误的误解吗? For instance, in the code below; 例如,在下面的代码中;

for (int check=3; check <= primeLimit; check += 2) {
    boolean divisorFound=false;
    for (int div=3; div<=Math.sqrt(check) && !divisorFound; div += 2) {
        if (check%div==0)
            divisorFound=true;
    }

Is the second for loop searching for divisorFound to be true of false? 搜索divisorFound的第二个for循环是否为true或false? Because if it was implying that the divisor is false, wouldn't it just say : 因为如果这暗示除数为假,那不是就说:

div<=Math.sqrt(check) && divisorFound;

I'm assuming you didn't write this code and are trying to understand what it's purpose is. 我假设您没有编写此代码,而是试图了解其目的。 The inner loop should continue until a divisor is found. 内部循环应继续直到找到除数。 So it repeatedly checks to see if !divisorFound evaluates to true . 因此,它反复检查!divisorFound评估结果是否为true In other words, "has a divisor not been found yet?". 换句话说,“有一个除数没有被发现了吗?”。

Once a divisor is found, divisorFound is set to true and the expression !divisorFound evaluates to false , so the loop will stop. 找到除数后,将divisorFound设置为true ,并且表达式!divisorFound计算结果为false ,因此循环将停止。

If the condition check that you suggested was used: 如果使用了您建议的条件检查:

div<=Math.sqrt(check) && divisorFound

The loop body would never be reached. 循环体将永远无法到达。 divisorFound is false to start with so the continue condition would immediately fail and the loop would terminate. divisorFoundfalse ,因此继续条件将立即失败并且循环将终止。

The second loop is saying to continue looping when div is less than Math.sqrt(check) and no divisor has been found. 第二个循环是说当div小于Math.sqrt(check)且未找到除数时继续循环。 When divisorFound has been set to true, then the inner loop will fail its condition. divisorFound设置为true时,内部循环将失败其条件。

I think you must have misread the code as this is a pretty straight forward boolean condition. 我认为您一定误读了代码,因为这是一个非常简单的布尔条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM