如何在 main 中调用 bool 函数?

How to call a bool function in main?

我正在尝试创建一个函数,通过它我可以检查输入的数据是否与三角形匹配。我设法完成了这个功能,但我在 main 中调用它时遇到了麻烦。我希望输出为真或假。 谢谢

#include <cs50.h>
#include <stdio.h>

bool triangle(float a, float b, float c);

int main(void)
{
// This is where I miss the point and need help with. A little explanation would be great. Thanks.
    printf("%d", triangle(3, -7, 8));
}

bool triangle(float a, float b, float c)
{
    if (a <= 0 || b <= 0 || c <= 0)
    {
        return false;
    }
    
    if ((a + b <= c) || (a + c <= b) || (c + b <= a))
    {
        return false;
    }

    return true;


}

你可以试试这个:

int main(void)
{
// This is where I miss the point and need help with. A little explanation would be great. Thanks.
   bool iden = triangle(3, -7, 8);
   if ( iden == true ) printf( "true" );
   else printf("false");
}

如果你使用

int main(void)
{
// This is where I miss the point and need help with. A little explanation would be great. Thanks.
    printf("%d", triangle(3, -7, 8));
}

你会得到0,因为它returnfalse.

所以,如果 return true,你会得到 1

当您的条件被验证为打印 true 或 false 时使用 printf

#include <stdbool.h>
#include <stdio.h>

bool triangle(float a, float b, float c);

int main(void)
{
// This is where I miss the point and need help with. A little explanation would be great. Thanks.
    if(triangle(3, -7, 8))
    printf("True");
    else printf("False");
}

bool triangle(float a, float b, float c)
{
    if (a <= 0 || b <= 0 || c <= 0)
    {
        return false;
    }
    
    if ((a + b <= c) || (a + c <= b) || (c + b <= a))
    {
        return false;
    }

    return true;


}

每当您使用 bool 时,最好添加一个额外的包含(因为 bool 在 C 中不是原始类型):

#include <stdbool.h>

(或者)你可以使用 _Bool 类型,它不需要任何额外的 headers.

你可以这样做:

#include <stdio.h>

_Bool triangle(float a, float b, float c);

int main(void)
{
    printf("%s", triangle(3, -7, 8) ? "true" : "false");
}

_Bool triangle(float a, float b, float c)
{
    if (a <= 0 || b <= 0 || c <= 0)
    {
        return 0;
    }
    
    if ((a + b <= c) || (a + c <= b) || (c + b <= a))
    {
        return 0;
    }

    return 1;


}

您可以使用条件运算符来评估此函数的 return。 if triangle returns true (1) - 将打印“true”。 否则,将打印“false”。

printf("%s", triangle(3, -7, 8) ? "true" : "false");