Reputation: 9
i am trying to find out the minimum difference between three integers. And it says:"Operator '&&' can't be applied to operands of type 'int' and 'bool'". Where i am wrong?
static void Main(string[] args)
{
int number1, number2;
Console.WriteLine("Enter three numbers.");
int x= int.Parse(Console.ReadLine());
int y= int.Parse(Console.ReadLine());
int z= int.Parse(Console.ReadLine());
if(Math.Abs(x-y) < Math.Abs(y-z) && Math.Abs(x-z))
{
number= x;
number= y;
}
else if....
Upvotes: 0
Views: 236
Reputation: 559
Math.Abs(x-z) on its own does not resolve to a boolean. If you are intending to use the integer representations of a boolean (0 is false, !0 is true) just cast
if(Math.Abs(x-y) < Math.Abs(y-z) && Convert.ToBoolean(Math.Abs(x-z)))
Upvotes: 0
Reputation: 1659
The problem is with Math.Abs(x-y) < Math.Abs(y-z) && Math.Abs(x-z)
, specifically && Math.Abs(x-z)
.
I assume what you're trying to say is that |x - y| < { |y - z| , |x - z| } or, in other words, the absolute value of x-y is less than the absolute value of y-z and also the absolute value of x-z.
< is an operator that takes two operands, in this case, two ints. && is another operator that takes two bool operands. To be able to express what you were trying to do, the && operator would have to be able to do more than just bools, because right now your && has a bool and int around it. This shows this a little clearer...
bool isLessThan = Math.Abs(x - y) < Math.Abs(y - z);
if (isLessThan && Math.Abs(x - z))
{
...
}
The if statement will have an error because the && operator doesn't know how to compare a bool and int. You should change it to this to fix it...
int xMinusY = Math.Abs(x - y);
if (xMinusY < Math.Abs(y - z) && xMinusY < MAth.Abs(x - z))
{
...
}
Upvotes: 3
Reputation: 29
static void Main(string[] args)
{
int number1, number2;
Console.WriteLine("Enter three numbers.");
int x = int.Parse(Console.ReadLine());
int y = int.Parse(Console.ReadLine());
int z = int.Parse(Console.ReadLine());
if ((Math.Abs(x - y) < Math.Abs(y - z)) && (Math.Abs(x - y) < (Math.Abs(x - z))
{
number1 = x;
number2 = y;
}
You can resolve this problem like this.
Upvotes: 2