简体   繁体   English

在while语句中理解逻辑表达式

[英]Comprehension of a logical expression in a while statement

I have code that reads numbers from keyboard and sums them and outputs the sum when the loop terminates. 我有从键盘读取数字并将其求和并在循环终止时输出总和的代码。 The loop terminates when the number inputed is negative and divisible by 2 or it is positive and divisible by 3. But it is not working correctly. 输入的数字为负数且可被2整除或为正数且可被3整除时,循环终止。但是,它不能正常工作。 Where is the problem in the while condition? while条件的问题在哪里?

while(!(n<0 && n%2==0) || !(n>0 && n%3==0))

This is related to the negating logical expressions. 这与否定逻辑表达式有关。 The most simple way is to write a positive expression and the negate it with ! 最简单的方法是编写一个肯定的表达式,然后用!取反! :

!((n<0 && n%2==0) || (n>0 && n%3==0))

After that you can open the parentheses using Boolean algebra rules: when you open a negation statement you add a negation before each component and replace OR with AND and vice versa: 之后,你可以使用布尔代数规则打开括号:当你打开一个否定陈述你的每个组件前添加一个否定和更换AND,反之亦然:

!(n<0 && n%2==0) && !(n>0 && n%3==0)

Using this rule you can continue opening the parentheses. 使用此规则,您可以继续打开括号。

!(n<0 && n%2==0) || !(n>0 && n%3==0)

NOT (n is negative AND n is divisible by 2) OR NOT (n is positive AND n is divisible by 3). NOT(n为负,n可以被2整除)或NOT(n为正,n可以被3整除)。

This is a logical error NOT (A OR B) is not the same as (NOT A or NOT B), it is equal to NOT A and NOT B. 这是一个逻辑错误NOT(A OR B)与(NOT A或NOT B)不同,它等于NOT A和NOTB。

Check out: http://integral-table.com/downloads/logic.pdf 检出: http : //integral-table.com/downloads/logic.pdf

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

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