karthik nair
karthik nair

Reputation: 224

Condition Returns True even if it isn't

So i was writing a C program to check if a triangle is scalene, isosceles,or equilateral. But whenever i equate the three sides NOT to be equal, it still returns 1 (see condition on line 16).

// Write a C program to check whether the triangle is equilateral, isosceles or scalene triangle
#include <stdio.h>

int main()
{
    int side1, side2, side3;
    printf("Enter side 1: ");
    scanf("%d", &side1);
    printf("Enter side 2: ");
    scanf("%d", &side2);
    printf("Enter side 3: ");
    scanf("%d", &side3);
    if (((side1+side2)>side3)&&((side2+side3)>side1)&&((side1+side3)>side2))
    {
        if (side1!=side2!=side3)
        {
            printf("%d\n", side1!=side2!=side3);
            if ((side1==side2)||(side1==side3)||(side2==side3))
            {
                printf("Triangle is isosceles!");
            }
            else
            {
                printf("Triangle is scalene!");
            }
        }
        else
        {
            printf("Triangle is equilateral!");
        }    
    }
    else
    {
        printf("Input sides doesn't make a triangle!");
    }
    printf("\n");
}

karthik@cosmic:~/.../Binaries (compiled on Linux)$ ./scalene\ equilateral\ or\ isosceles 
Enter side 1: 34
Enter side 2: 34
Enter side 3: 34
1
Triangle is isosceles!

I dont understand why that '1' should be printed or why should that line of loop work. Someone please help me!

Upvotes: 0

Views: 61

Answers (1)

sagi
sagi

Reputation: 40491

You are printing the same expression that you use in the if condition, so if the if expression is true, it will obviously print 1..

    if (side1!=side2!=side3)
    {
        //If you got here, then side1!=side2!=side3 returns 1.
        printf("%d\n", side1!=side2!=side3);

More over, side1 != side2 will return either 1 or 0. Then you check if (1 or 0) != side3, which will probably be true, and return 1. If you enable warnings the compiler will probably throw a warning..

You probably want side1 != side2 && side1 != side3 && side2 != side3

Upvotes: 4

Related Questions