Reputation: 8433
I wrote a piece of code which attempts to tell which of three user-inputted numbers is the greatest. However, I am unable to understand why my code breaks for the input 3, 1, 2
and works for the input 55, 54, 56
.
My code:
main()
{
int a,b,c;
printf("enter three numbers");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is greatest",a);
if(b>a && b>c)
printf("%d is greatest",b);
else printf("%d is greatest",c);
getch();
}
What am I doing that causes this error, and what can I do to fix it?
Upvotes: 0
Views: 259
Reputation: 472
#define MAX(a,b) (((a)>=(b))?(a):(b))
#define MAX3(a,b,c) MAX(MAX(a,b),c)
Upvotes: 0
Reputation: 2228
Why don't you try this. Its neater. The problem with your code was that you were missing an else which could have been put along with if.
main() {
int a,b,c;
printf("enter three numbers");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is greatest\n",a);
else if(b>c)
printf("%d is greatest\n",b);
else printf("%d is greatest\n",c);
//getch();
}
Upvotes: 0
Reputation: 318
try this
condition? exp1: exp2;
evaluates to
if condition is true then return exp1 else return exp2
int main(){
int a,b,c;
printf("enter three numbers");
scanf("%d %d %d",&a,&b,&c);
int d = (a >= b)? a: b;
d = (d >= c)? d: c;
printf("%d is greatest", d);
}
Upvotes: 1
Reputation: 167
Just add a simple else if statement to your code and it should work fine as in :
main() {
int a,b,c;
printf("enter three numbers");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is greatest\n",a);
else if(b>a && b>c)
printf("%d is greatest\n",b);
else printf("%d is greatest\n",c);
//getch();
}
Upvotes: 0
Reputation: 19443
What people say here are true, but for best practice I would reduce the checks in the ifs:
main()
{
int a,b,c;
printf("enter three numbers: ");
scanf("%d %d %d",&a,&b,&c);
if(a>=b) //it's not b.
{
if(a>=c)
{
printf("%d is greatest",a);
}
else
{
printf("%d is greatest",c);
}
}
else // here you know that b > a, then it's not a.
{
if(b>=c)
{
printf("%d is greatest",b);
}
else
{
printf("%d is greatest",c);
}
}
}
Upvotes: 1
Reputation: 1343
You need to add an else
before the line if(b>a && b>c)
.
i.e.
if(b>a && b>c)
should be
else if(b>a && b>c)
Upvotes: 1
Reputation: 2326
You are missing "else if", that's for sure.
main()
{
int a,b,c;
printf("enter three numbers: ");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is greatest",a);
else if(b>a && b>c)
printf("%d is greatest",b);
else
printf("%d is greatest",c);
}
Upvotes: 1