Furkan
Furkan

Reputation: 357

Comparing three numbers given by user in C

I was trying to compare three integers equality as three different outputs. First, all are equal; second, all are different; and third, neither of them. I just tried to do it like that but this code works wrong for some numbers such as 4,5,5 other combinations work fine. How can I resolve the problem?

#include<stdio.h>
int main() {
    int a,b,c;
    printf("Please enter three numbers:");
    scanf("%d%d%d",&a,&b,&c);
    if(a==b && b==c) {
        printf("All numbers are equal.");
    } 
    else if(a!=b && b!=c && a!=c) printf("All numbers are different.");
    
    else if(a=b) {
        if(b!=c) printf("Neither all are equal or different.");
    }
    
    else if(a=c) {
        if(c!=b) printf("Neither all are equal or different.");
    }
    else if(b=c) {
        if(b!=a) printf("Neither all are equal or different.");
    }

    
    return 0;
}

Upvotes: 1

Views: 3037

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

Aside from the 'typos' in your last three else if tests (= is an assignment, but you need the comparison operator, ==), those three tests are actually unnecessary.

If the first two tests both fail, then you already know that the third option is the case. So your code can be reduced to something like this:

#include<stdio.h>
int main()
{
    int a, b, c;
    printf("Please enter three numbers:");
    scanf("%d%d%d", &a, &b, &c);
    if (a == b && b == c) {
        printf("All numbers are equal.");
    }
    else if (a != b && b != c && a != c) {
        printf("All numbers are different.");
    }
    else {
        printf("Neither all are equal nor all are different.");
    }
    return 0;
}

Upvotes: 2

Related Questions