Monday, 2 September 2013

simple program to determine type of triangle giving weird results

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 :
int comparator (const void * elem1, const void * elem2) {
int f = *((int*)elem1);
int s = *((int*)elem2);
if (f > s) return 1;
if (f < s) return -1;
return 0;
}
void checkTriangles(float *num){ // num[] is a sorted array
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");
}
}
however , im getting real odd outputs like this :

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.
also , i have only kept this much code as i was getting an auto generated
warning that code proportion was much greater than the actual description.
will provide the rest of the code if needed.
edit : the main() method
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;
}

No comments:

Post a Comment