c - c 中的 IF 或 boolean 语句

标签 c if-statement boolean

我被一个问题困扰了一段时间。我正在尝试编写允许用户输入一个值的代码,如果其中两个值相同,则应显示“这是一个完美的正方形”的输出,但如果显示三个值,则应显示“这是一个完美的立方体”被显示。到目前为止,我对我所做的事情有点困惑,但是当我输入输入值时,有时我会收到正确的答案,或者它将显示我的所有 printf 输出。我似乎无法理解这种情况,并且确实需要一些帮助来理解。怎么布置呢。目前我正在用 C 语言编写,我是一名初学者程序员,我已经包含了到目前为止我所做的事情的屏幕截图,如果有人能告诉我哪里出了问题,那将非常有用。

到目前为止我的代码

    #include <stdio.h>

int main (void)

{

    int Height;
    int Width;
    int Depth;

    printf("Please insert value\n");
    scanf("%d%d%d", &Height, &Width, &Depth);

    if(Height == Width)
    {
        printf("It's a square cuboid\n");
    }
    else if(Height == Depth)
    {
        printf("It's a square cuboid\n");
    }
    else if(Width == Depth)
    {
        printf("It's a square cuboid\n");
    }
}

谢谢哈德利

最佳答案

您可以使用 &&|| 运算符链接 boolean 语句。例如,如果您想检查它是否是一个完美的立方体:

//If Height equals width AND height equals depth
if(Height == Width && Height == Depth)
{
    printf("Perfect Cube!");
}

或者如果你想检查它是否是一个完美的正方形:

if(Height == Width && Depth == 0)
{
    printf("Perfect Square!");
}

因此,将所有这些放在一起,验证输入后,您只需弄清楚哪些检查的作用即可。

int Height;
int Width;
int Depth;

printf("Please insert value\n");

if(scanf("%d%d%d", &Height, &Width, &Depth) != 3)
{
    printf("Wrong number of inputs");
    return -1;
}

//this            AND  this
if(Height == Width && Depth == 0)
{
    printf("Perfect Square!");
}//     this           AND   this
else if(Height == Width && Height == Depth)
{
    printf("Perfect Cube!");
}//     This             OR  this           OR this           then...
else if (Height == Width || Height == Depth || Width == Depth)
{
    printf("Square-faced cuboid!");
}

关于c - c 中的 IF 或 boolean 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379591/

相关文章:

c - 当时间过去时真正杀死当前进程

c - 在C中使用递归函数,为什么下面程序的输出是012345?

javascript - 中断函数 if , if 条件没有通过

c++ - 将短路评估转换为非短路评估

c - 在 C 中按升序对数组的前 k 个元素进行排序,其余元素按降序排序

c - 逐行读取数组中的文件

python - 在 Python 中跳过代码行?

java - if, else 语句实际上不起作用

c - 尝试在 C 中创建基本数组实用程序

Java 中的整数、字符串和 double