【问题标题】:C question in logical OR: 2 operands evaluated (0) false, but the result works as TRUE range逻辑 OR 中的 C 问题:2 个操作数评估 (0) 为假,但结果为 TRUE 范围
【发布时间】:2021-06-25 07:02:42
【问题描述】:

我的疑问是关于“或逻辑运算符”的基本理论。具体来说,只有当任一操作数为真时,逻辑或才会返回真。

例如,在这个 OR 表达式 (x 8) 中,当我计算 2 操作数时使用 x=5,我将其解释为它们都是错误的。

但我有一个不符合其规则的示例。相反,表达式的工作范围在 0 到 8 之间,两者都包括在内。 按照代码:

#include <stdio.h> 
int main(void) 
    { 
    int x ; //This is the variable for being evaluated 
    do 
    { 
    printf("Imput a figure between 1 and 8 : "); 
    scanf("%i", &x);
    }
    while ( x < 1 ||  x > 8);  // Why this expression write in this way determinate the range???
    {
    printf("Your imput was ::: %d ",x);
    printf("\n");
    }
    printf("\n");
    }

我修改了我的第一个问题。我非常感谢任何帮助以澄清我的疑问

提前,非常感谢您。奥托

【问题讨论】:

  • 逻辑或实际上是计算第一个表达式,如果为真,则返回真,如果为假,则计算第二个表达式。再次应用逻辑。
  • 谢谢,但在这种情况下,尽管两个操作数都为假,但表达式的结果为真

标签: operator-overloading expression


【解决方案1】:

这不是while 循环;这是一个do ... while 循环。格式很难看。重新格式化:

#include <stdio.h> 

int main(void) { 
    int x;

    // Execute the code in the `do { }` block once, no matter what.
    // Keep executing it again and again, so long as the condition
    // in `while ( )` is true.
    do { 
        printf("Imput a figure between 1 and 8 : "); 
        scanf("%i", &x);
    } while (x < 1 ||  x > 8);

    // This creates a new scope. While perfectly valid C,
    // this does absolutely nothing in this particular case here.
    {
        printf("Your imput was ::: %d ",x);
        printf("\n");
    }

    printf("\n");
}

带有两个printf 调用的块不是循环的一部分。 while (x &lt; 1 || x &gt; 8) 使得do { } 块中的代码运行,只要 x &lt; 1x &gt; 8。换句话说,它运行直到x 介于18 之间。这样的效果是要求用户一次又一次地输入一个数字,直到他们最终输入一个介于18 之间的数字。

【讨论】:

    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2012-01-18
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    相关资源
    最近更新 更多