Trying to check if an integer value falls into a range however it is giving me a compile time error
Operator '<=' cannot be applied to operands of type 'bool' and 'int'
int n = 3; // read from user like Convert.ToInt32(Console.ReadLine().Trim());
if ( 2 <= N <= 5)
{
Console.WriteLine("In range");
}
What is the correct way to check if a value falls into a range and why the way I wrote the check causes this error?
CodePudding user response:
You can't do this:
(2<=N<=5)
You have to do it as two:
(2<=N && N<=5)
(Trying to do it as one means c# will resolve the 2<=N
to some boolean, e.g true
and then try to do true<=5
- this gives rise to the error that "<= cannot be used to compare a boolean to an integer")
CodePudding user response:
This doesn't work they way you think it does:
(2<=N<=5)
What really happens here is the compiler first evaluates the 2<=N
part of the expression as producing a boolean result. It then wants to use this boolean result for the <=5
part of the expression... and that's not allowed. C# does not let you implicitly compare a boolean with an integer, and even if it did it's doubtful the result would match your intention for the code.
Instead, you need to do this:
if( (2 <= N && N <= 5) || N > 20 )
The same applies to the 6<=N<=20
expression.
Finally, I might reduce the logic to eliminate nesting and repeated outcomes, like this:
int N = Convert.ToInt32(Console.ReadLine().Trim());
if(N % 2 !=0 || (6 <= N && N <= 20 ))
{
Console.WriteLine("Not Weird");
}
else if( (2 <= N && N <= 4) || N >20 ) //4 rather than 5, because we know N is even
{
Console.WriteLine("Weird");
}
else // N is even and <=0
{
Console.WriteLine();
}