/** * triangle s1 s2 s2 - given three sides of the triangle, classifies * the triangle. */ #include #include // +-----------+------------------------------------------------------- // | Utilities | // +-----------+ /** * max(x,y) - compute the larger of x and y. */ int max (int x, int y) { return x > y ? x : y; } // max /** * min(x,y) - compute the smaller of x and y */ int min (int x, int y) { return x < y ? x : y; } // min /** * usage() - print a usage message. */ void usage () { printf ("Usage: triangle side1 side2 side3\n"); printf (" where side1, side2, and side3 are integers.\n"); } // usage() // +------+------------------------------------------------------------ // | Main | // +------+ int main (int argc, char *argv[]) { int sides[3]; // The three sides of the triangle int perimeter; // The perimiter of the triangle int shortest; // The shortest side int middle; // The middle side int longest; // The longest side int errors = 0; // A count of errors int i; // Everyone's favorite counter variable // Check number of parameters if (argc != 4) { usage (); return EXIT_FAILURE; } // Read the three sides for (i = 0; i < 3; i++) { if (sscanf (argv[i+1], "%d", &(sides[i])) != 1) { printf ("For side%d received \"%s\", which is not an integer.\n", i+1, argv[i+1]); ++errors; } // if } // for if (errors) { usage (); return EXIT_FAILURE; } // Sanity checks for (i = 0; i < 3; i++) { if (sides[i] <= 0) { printf ("Invalid side length: %d.\n", sides[i]); ++errors; } // if } // for if (errors) { usage (); return EXIT_FAILURE; } // Classify the sides perimeter = sides[0] + sides[1] + sides[2]; longest = max (max (sides[0], sides[1]), sides[2]); shortest = min (min (sides[0], sides[1]), sides[2]); middle = perimeter - longest - shortest; // Sanity check: Non-triangle and degenerate triangle if (shortest + middle < longest) { printf ("There is no triangle with side lengths %d, %d, and %d.\n", sides[0], sides[1], sides[2]); return EXIT_FAILURE; } if (shortest + middle == longest) { printf ("That's a degenerate triangle. What does that say about you?\n"); return EXIT_FAILURE; } // Start output printf ("The triangle with side lengths %d, %d, and %d is ", sides[0], sides[1], sides[2]); // Obtuse, acute, right if (shortest*shortest + middle*middle < longest*longest) printf ("an obtuse "); else if (shortest*shortest + middle*middle > longest*longest) printf ("an acute "); else printf ("a right "); // Equilateral, isosceles, scalene if (shortest == longest) printf ("equilateral "); else if ((shortest == middle) || (middle == longest)) printf ("isosceles "); else printf ("scalene "); // Other characteristics? printf ("triangle\n"); // And we're done. return EXIT_SUCCESS; } // main