首页 > 解决方案 > 逻辑 OR 中的 C 问题:2 个操作数评估 (0) 为假,但结果为 TRUE 范围

问题描述

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

例如,在这个 OR 表达式 (x<O || 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-overloadingexpression

解决方案


It's not a while loop; it's a do ... while loop. The formatting makes it hard to see. Reformatted:

#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");
}

The block with the two printf calls is not part of the loop. The while (x < 1 || x > 8) makes it so that the code in the do { } block runs, so long as x < 1 or x > 8. In other words, it runs until x is between 1 and 8. This has the effect of asking the user to input a number again and again, until they finally input a number that's between 1 and 8.


推荐阅读