逻辑 (布尔) 运算符

逻辑表达式 (例如,比较表达式) 在处理时返回 1 (true) 或 0 (false)。 逻辑运算符组合两个比较,并根据比较结果返回 10

逻辑运算符

运算符
含义
&
如果两个比较都为 true ,那么返回 1 。 例如:
(4 > 2) & (a = a) /* true, so result is 1 */

(2 > 4) & (a = a) /* false, so result is 0 */
|
包含 OR
如果至少有一个比较为 true ,那么返回 1 。 例如:
(4 > 2) | (5 = 3) /* at least one is true, so result is 1 */

(2 > 4) | (5 = 3) /* neither one is true, so result is 0 */
&&
互斥 OR
如果仅一个比较 (但不能同时两个比较) 为 true ,那么返回 1 。 例如:
(4 > 2) && (5 = 3) /* only one is true, so result is 1 */

(4 > 2) && (5 = 5) /* both are true, so result is 0 */

(2 > 4) && (5 = 3) /* neither one is true, so result is 0
*/
前缀 \ , ¬
逻辑非
求反-返回相反的响应。 例如:
\ 0 /* opposite of 0, so result is 1 */

\ (4 > 2) /* opposite of true, so result is 0 */

使用逻辑表达式

您可以在复杂的条件指令中使用逻辑表达式,并将其作为检查点来筛选不需要的条件。 当您有一系列逻辑表达式时,为了进行说明,请使用一组或多组括号将每个表达式括起来。
IF ((A < B) | (J < D)) & ((M = Q) | (M = D)) THEN ....
以下示例使用逻辑运算符来制定决策。
图 1。 使用逻辑表达式的示例

/****************************** REXX ********************************/
/* This program receives arguments for a complex logical expression */
/* that determines whether a person should go skiing. The first     */
/* argument is a season and the other two can be 'yes' or 'no'.     */
/********************************************************************/

PARSE ARG season snowing broken_leg

IF ((season = 'WINTER') | (snowing ='YES')) & (broken_leg ='NO')
   THEN SAY 'Go skiing.'
ELSE
   SAY 'Stay home.'
当传递到此示例的参数为 SPRING YES NO 时, IF 子句将按如下所示进行转换:

IF ((season = 'WINTER') | (snowing ='YES')) & (broken_leg ='NO') THEN  
      \______________/     \____________/      \_____________/
          false                true                 true
            \___________________/                    /      
                    true                            /
                     \_____________________________/
                                 true
因此,当您运行该程序时,它将生成以下结果:
Go skiing.

练习: 使用逻辑表达式

申请高校的学生根据以下规范决定对其进行评估:
IF (inexpensive | scholarship) & (reputable | nearby) THEN
   SAY "I'll consider it."
ELSE 
   SAY "Forget it!"

一所大学便宜,没有提供奖学金,声誉卓着,但远在 1000 英里之外。 学生应该申请吗?

答案

是。 条件指令的作用如下:

IF (inexpensive | scholarship) & (reputable | nearby) THEN ... 
    \__________/ \___________/   \_________/ \______/
       true          false          true      false
          \___________/               \_________/
              true                       true    
                \_________________________/
                           true