C语言 如何在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;

}

您可以使用条件运算符来计算此函数的返回。 如果三角形返回 true (1( - 将打印"true"。 否则,将打印"假"。

printf("%s", triangle(3, -7, 8) ? "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类型,它不需要任何其他标头。

你可以做这样的事情:

#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;

}

你可以试试这个:

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,因为它返回false

所以,如果它返回true,你会得到1

最新更新