I have in my code the specificacions of the bool to return true or false but I don't figure how to printf depending if it is true or false. I have some float prompted by the user and the bool to determine if it is true or false. How can I use these both datas to printf depending?
bool valid_triangle(float x, float y, float z);
int main(void)
{
float x;
float y;
float z;
do
{
x = get_float("Enter a length: ");
}
while(x <= 0);
do
{
y = get_float("Enter other length: ");
}
while(y <= 0);
do
{
z = get_float("The last one: ");
}
while(z <= 0);
}
if(valid_triangle = 1)
{
printf("It's a triangle");
}
bool valid_triangle(float x, float y, float z)
{
if(x <= 0 || y <= 0 || z <= 0)
{
return false;
}
if((x y <= z) || (x z <= y) || (y z <= x))
{
return false;
}
return true;
}
I tried an if conditional with the bool but doesn`t compile.
CodePudding user response:
This:
if(valid_triangle = 1)
tries to re-assign the valid_triangle
function to the integer 1. That does not compile; the names of functions behave like constants and cannot be assigned to.
You need something like:
if (valid_triangle(x, y, z))
{
printf("yay, got a valid triangle with sides %f, %f and %f!\n", x, y, z);
}
The above calls the valid_triangle()
function, passing it the three values you collected from the user. If the return vale is non-zero (which true
is), the if
will execute its body, otherwise it will be skipped.
Note that I (strongly) advise against explicit comparisons against booleans, since the comparison operator itself simply results in a boolean value which makes it feel painfully recursive to me. I also don't think it's any clearer.
CodePudding user response:
Your valid_triangle function expects 3 arguments x, y, z. You have to pass the values you take from user to the function.
if(valid_triangle(x, y, z) == true)
{
printf("It's a triangle");
} else {
printf("It's not a triangle");
}