Somjit
Somjit

Reputation: 2772

simple program to determine type of triangle giving weird results

the program checks simple triangle types : equilateral , isosceles , right-angled etc . but im getting really weird results.

my code :

#include <stdio.h>
#include <stdlib.h>
int comparator (const void * elem1, const void * elem2) {
    int f = *((float*)elem1);
    int s = *((float*)elem2);
    if (f > s) return 1;
    if (f < s) return -1;
    return 0;
}
void checkTriangles(float *num){
    float a = *num;
    float b = *(num + 1);
    float c = *(num + 2);

    if((a*a + b*b)==c*c){
        printf("right angled triangle");
    }
    else if(a==b || b==c || c==a){
        printf("isosceles triangle");
    }
    else if(a==b && b==c){
        printf("equilateral triangle");
    }
    else if(a!=b && b!=c && c!=a && ((a+b)>c)){
        printf("normal triangle");
    }
    else{
        printf("invalid");
    }
}

int main(void){
    char c = 'a';
    char str[12];
    float num[3];
    while(c!='q'){
        printf("\n\nenter the sides : ");
        fgets(str , sizeof(str) , stdin);
        sscanf(str , "%f%f%f", num , num + 1 , num + 2);

        qsort(num, sizeof(num)/sizeof(*num), sizeof(*num), comparator);
        printf("\n%f\n%f\n%f\n", num , num + 1 , num + 2);

        checkTriangles(num);

        printf("\nenter q to quit.. any other to continue : ");
        c=getchar();
    }
    return 0;
}

however , im getting real odd outputs like this :

enter image description here

i know that using quick sort for something like this is overkill , but i wanted to keep it short and use comparators also, just for fun.

edit : iv added the full code , and checked the comparator to check for floats , but still getting the same output.

Upvotes: 0

Views: 2131

Answers (2)

AlexJ136
AlexJ136

Reputation: 1282

The if condition:

else if(a==b || b==c || c==a){
    printf("isosceles triangle");
}

Will evaluate to true for isosceles triangles AND equilateral triangles - when you pass a = 5, b = 5, c = 5, this if-condition evaluates to true and isosceles is printed. You want something like:

else if( (a==b || b==c || c==a) && !(a==b && a==c){
    printf("isosceles triangle");
}

And then when you give an equilateral triangle, you will get the correct thing printed.

Alternatively you could just put the equilateral case before the isosceles case, but that'd be bad practice. Explicit is always better than implicit.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

Here is a big problem which is undefined behavior:

printf("\n%f\n%f\n%f\n", num , num + 1 , num + 2);

Here you use the pointers to the values in the printf call, but you should use the values.

Change to e.g.

printf("\n%f\n%f\n%f\n", num[0], num[1], num[2]);

Note: There's no need to keep using pointer dereference, you have an array so why not use array syntax?

Upvotes: 6

Related Questions