zeeks zeeks - 2 months ago 6
C Question

find if the triangle is right, acute or obtuse angled

I have to find out if a triangle is right, acute or obtuse angled from 3 given side lengths of the triangle.

This is what I have until now:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Program that calculates the type of triangle
int main(int argc, char *argv[]) {

int x,y,z;

printf("Type in the integer lengths of 3 sides of a triangle:\n");
scanf("%d %d %d", &x, &y, &z); //reads the user's inputs
if((x<=0) || (y<=0) || (z<=0)) {
printf("This is not a triangle.\n");
} else {
if((x + y <= z) || (x + z <= y) || (y + z <= x)) {
printf("This is not a triangle.\n");
} else {

if( ((x * x) + (y * y) == (z * z)) || ((x * x) + (z * z) == (y * y)) || ((z * z) + (y * y) == (x * x)) ) {
printf("This is a right-angled triangle.\n");
} else if( ( ((x * x) + (y * y) < (z * z)) || ((x * x) + (z * z) < (y * y)) || ((z * z) + (y * y) < (x * x)) ) || ( ( x<=z && y<=z ) || ( x<=y && z<=y ) || ( y<=x && z<=x ) ) ) {
printf("This is an acute-angled triangle.\n");
} else if( ( ((x * x) + (y * y) > (z * z)) || ((x * x) + (z * z) > (y * y)) || ((z * z) + (y * y) > (x * x)) ) || ( ( x>z && y>z ) || ( x>y && z>y ) || ( y>x && z>x ) ) ) {
printf("This is an obtuse-angled triangle.\n");
} else {
printf("Not a triangle\n");
}

}
}

return 0;
}


But I keep receiving the same error "This is an acute-angled triangle" for obtuse-angled triangles like 10, 10, 11

Any idea what I am doing wrong?

Thank you

Answer

I've simplified your code, by finding the longest side first, and removing most of the comparisons (and brackets).

But most importantly, your squares comparison for acute and obtuse was the wrong way round. The sum of the smaller sides' squares is greater than the longest, for an acute triangle.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Program that calculates the type of triangle
int main(int argc, char *argv[]) {

    int x,y,z,longest;

    printf("Type in the integer lengths of 3 sides of a triangle:\n");
    scanf("%d %d %d", &x, &y, &z); //reads the user's inputs
    if((x<=0) || (y<=0) || (z<=0)) {
      printf("This is not a triangle.\n");
    } else {
        if((x + y <= z) || (x + z <= y) || (y + z <= x)) {
        printf("This is not a triangle.\n");
        } else {

            longest = z;
            if (longest < x) {
                z = longest;
                longest = x;
                x = z;
            }
            if (longest < y) {
                z = longest;
                longest = y;
                y = z;
            }

            if( x * x + y * y == longest * longest ) {
                printf("This is a right-angled triangle.\n");
            } else if( x * x + y * y > longest * longest) {
                printf("This is an acute-angled triangle.\n");
            } else printf("This is an obtuse-angled triangle.\n");
        }
  }

  return 0;
}