-
You are casting
(bool) valid_triangel
the address of the function instead of calling it. This will always be non-NULL and the corresponding true branch of the if condition will be executed irregardless of input. -
(non-issue) I don’t have cs50.h installed so I wrote a quick
get_double()
to test your code. -
Removed the declaration of
valid_tringel()
insidemain()
. -
Fixed typo (triangle).
-
(x + y >= z ) || (x + z >= y) || (z + y >= x )
is inverted invalid_triangle()
. As you return boolean just express is directly instead of anif
condition:
According to the first triangle inequality theorem, the lengths of any two sides of a triangle must add up to more than the length of the third side.1
- Used early return style in
main()
so the normal case is not indented (purely a matter of style).
#include <stdio.h>
#include <stdbool.h>
double get_double(const char *s) {
printf("%s", s);
double d;
scanf("%lf", &d);
return d;
}
bool valid_triangle(double x, double y, double z) {
return
x > 0 &&
y > 0 &&
z > 0 &&
x + y > z &&
x + z > y &&
z + y > x;
}
int main(void) {
double a = get_double("give me first length : ");
double b = get_double("give me second length : ");
double c = get_double("give me third length : ");
if(!valid_triangle(a, b, c)) {
printf("THIS IS NOT VALID\n");
return 0;
}
printf("THAT IS A TRIANGLE\n");
}
and here is example output:
give me first length : -1
give me second length : 1
give me third length : 10
THIS IS NOT VALID
give me first length : 1
give me second length : 2
give me third length : 3
THIS IS NOT VALID
give me first length : 7
give me second length : 10
give me third length : 5
THAT IS A TRIANGLE
solved Every time I start the project always just writes that ” THIS IS NOT VALID” even if the numbers that I give are right [closed]