I have an if statement as follows
if (1 <= value <= 20)
{
}
value is a double.
however I get an error which says that "Operator '<=' cannot be applied to operands of type 'bool' and 'double'"
Is there a way around this error?
C# doesn't allow you to do this.
Do like this:
if (1 <= value && value <= 20)
The problem is not the double, problem is your syntax is incorrect.
You:
if (1 <= value <= 20)
{
}
That is interpreted as
(1 <= value) <= 20
so first 1 will be compared with value and it will be determined if the former is "less than or equal" the latter. That gives a boolean. Then that boolean, True or False, is compared with <= to 20. But you cannot ask if True/False is less than or equal 20, in C#.
Problem : you can not check two expressions without Combining them.
Solution : i think you want to check whether value is in beteween 1 and 20
You can Use Logical AND && operator for checking this
Try This:
if (value >= 1 && value <= 20)
{
}
1 <= value evaluates out to be bool (false if value is less than 1 and true otherwise).
So it evaluates out to be (true <= 20) or (false <=20) and error states clearly that you cannot use operator <= to compare bool and double.
You need and (&&) operator to do comparison:
if (1 <= value && value <= 20)
{
}
Related
This question already has answers here:
C# conditional AND (&&) OR (||) precedence
(6 answers)
Closed 3 years ago.
I'm going through some C# coding exercises and have run into some operator logic that's stumped me.
The following line of code evaluates to false:
int a = 40, int b = 50;
if (a >= 20 && a <= 30 && (b < 20 || b > 30))
{
return a;
}
However, if I remove the brackets from inside the if statement, it evaluates to true.
if (a >= 20 && a <= 30 && b < 20 || b > 30)
{
return a;
}
Can anyone explain what I'm missing? Given that a isn't between 20 and 30, shouldn't it return false? I don't understand why putting the b portion of the if statement in brackets makes it evaluate to false.
Is it evaluating everything prior to "b > 30" as a single condition?
This is all to do with operator precedence.
Just like how * are evaluated first before + (we say * has a higher precedence than +), && is evaluated before ||, as specified.
In the first code snippet, you used brackets to "override" this precedence, making the || part evaluate first, just like how you can add parenthesis to the expression 1 + 2 * 3 to make it evaluate to 9 instead of 7.
a >= 20 && a <= 30 && (b < 20 || b > 30)
^^^^^^^^^^^^^^^^^
this part first
which becomes:
a >= 20 && a <= 30 && true
^^^^^^^ ^^^^^^^
now these parts
which becomes:
false && false && true
resulting in false.
In the second example however, there are no parentheses so the expression is evaluated according to the normal precedence rules:
a >= 20 && a <= 30 && b < 20 || b > 30
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This part first
Which becomes:
false || b > 30
^^^^^^
then this
which becomes:
false || true
resulting in true.
If you look at the second part where you have removed the parenthesis, it is now divided into two subparts.
First one being : a >= 20 && a <= 30 && b < 20 This evaluates to false.
First one being : b > 30 This statement evaluates to true.
So at the end you have something like this
F || T from both the statements which should eventually give you true as end result
I have a datetime definition that I do not know how to use of. What exactly is the expression between the <> signs? it returns Boolean but how?
bool x= DateTime.Now.AddDays(20) <DateTime.Now && DateTime.Now.AddDays(10)> DateTime.Now;
Format it differently and it will be easy to see that it's two less than/greater than signs:
bool x = DateTime.Now.AddDays(20) < DateTime.Now
&& DateTime.Now.AddDays(10) > DateTime.Now;
bool x = DateTime.Now.AddDays(20) < DateTime.Now //(1)
&& DateTime.Now.AddDays(10) > DateTime.Now; //(2)
To English:
(1): Is (Today + 20 days) smaller than Today?
// We have False
(2): Is (Today + 10 days) greater than Today?
// We have True
And Finally (1) && (2) will return your result x
// We have x = True && False = False
What exactly is the expression between the <> signs? it returns Boolean but how?
As already mentioned in the code that you posted < and > and && are operators and not tags
the first < is a "less than" relational operator
the last > is a "greater than" relational operator
These operators compare the operands at each side of the operator and return true or false.
the middle operator && is called The conditional-AND operator and it
performs a logical-AND of its bool operands
This is why the whole statement returns bool
I've been presented what I think is an ANSI C statement but I don't understand what it is doing or if it is even valid.
x = (y == 4) * 12 + (y == 5) * 24;
Can anyone help me understand what this statement does in terms of C# (which I actually understand).
Thanks
Historically, C did not have a boolean type.* Comparison operators returned either 0 or 1, type int. Any int value (as well as other types) could be interpreted in boolean context, where 0 means false and any other value means true.
C# treats int and bool as completely separate types. The most direct C# equivalent is
x = (y == 4 ? 1 : 0) * 12 + (y == 5 ? 1 : 0) * 24;
Which can of course be improved greatly further.
* Typically, "ANSI C" is intended to refer to the original version of C, even though later versions of C have been adopted by ANSI too. Those later versions do add a boolean type, but the comparison operators still return int values. Similarly, integers in boolean contexts are still allowed as well. They do not change anything relevant to your question.
This is definitely wrong in C#. Both expressions, y==4 and y==5 are evaluated as a boolean. That being said, how can you define the multiplication between a boolean and an integer? This expression is not correct in C#.
I would say that you could try the following:
x = (y == 4 ? 1 : 0) * 12 + (y == 5 ? 1 : 0) * 24;
In the above expression we use the ternary operator, whose logic is quite simple it the expression evaluates to true then return the result after the question mark. Otherwise it returns the value after the :. So if y is equals to 4, then (y == 4 ? 1 : 0) evaluates to 1. Otherwise, it returns 0.
The above solution is based on that hvd mentioned below in his comment, that == returns either 0 or 1 in C.
I was writing a program which takes input from the keyboard and prints a square matrix in the following spiral manner
1 2 3
8 9 4
7 6 5
I managed to write the program but I encountered a weird error.
in line 26 it gives me an index out of bound exception
while (matrix[row, col] == 0 && col < matrix.GetLength(0) )
However if I switch the order of the two statements inside the loop the exception is gone ? Does this mean that the order of the two statements in the while loop is important ? And if yes , why ? Shouldn't it be if both statements are true to execute the loop, and if one of them is false, no matter which one, to stop executing it.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpiralMatrixN
{
class Program
{
static void Main(string[] args)
{
//prompt the user to enter n
Console.WriteLine("Enter the value of n");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n,n];
Console.Clear();
System.Console.SetWindowSize(100, 30);
int value = 1;
int col = 0;
int row = 0;
if (n>0 && n<21)
{
while(value <= n*n)
{
while (matrix[row, col] == 0 && col < matrix.GetLength(0) )
{
matrix[row, col++] = value;
value++;
}
col--;
row++;
while (row < matrix.GetLength(1) && matrix[row, col] == 0)
{
matrix[row++, col] = value;
value++;
}
row--;
col--;
while (col >= 0 && matrix[row, col] == 0 )
{
matrix[row, col--] = value;
value++;
}
col++;
row--;
while (matrix[row, col] == 0 && row >= 0)
{
matrix[row--, col] = value;
value++;
}
col++;
row++;
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.SetCursorPosition(j * 5, i * 2);
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
}
Yes, order is important. Conditions in the && clause are executed in the order of precedence, and if one fails another is not executed. Currently what you have fails because matrix[row, col] == 0 is executed first, and col comes out of bounds. So your check for col (which is absolutely correct btw) should come first:
while (col < matrix.GetLength(0) && matrix[row, col] == 0)
If it fails, second statement won't be executed and you won't have an error. This is called "short-circuit evaluation".
Yes, it is called short circuit evaluation. Since you are using "&&", the second condition gets evaluated only after the first one evaluates to true.
The order in && is important && uses short-circuiting vs & which does not. In an && expression from left to right if a condition is false the other conditions are not evaluated.
Conditional logical operators
The && and || operators are called the conditional logical operators.
They are also called the "short-circuiting" logical operators.
conditional-and-expression:
inclusive-or-expression
conditional-and-expression && inclusive-or-expression
conditional-or-expression:
conditional-and-expression
conditional-or-expression || conditional-and-expression*
The && and || operators are conditional versions of the & and |
operators:
The operation x && y corresponds to the operation x & y,
except that y is evaluated only if x is true.
The operation x || y corresponds to the operation x | y, except that y
is evaluated only if x is false.
An operation of the form x && y or x || y is processed by applying
overload resolution (Section 7.2.4) as if the operation was written x
& y or x | y. Then,
If overload resolution fails to find a single best
operator, or if overload resolution selects one of the predefined
integer logical operators, a compile-time error occurs.
Otherwise, if the selected operator is one of the predefined Boolean
logical operators (Section 7.10.2), the operation is processed as
described in Section 7.11.1.
Otherwise, the selected operator is a user-defined operator, and the
operation is processed as described in Section 7.11.2.
It is not possible to directly overload the conditional logical operators.
However, because the conditional logical operators are evaluated in
terms of the regular logical operators, overloads of the regular
logical operators are, with certain restrictions, also considered
overloads of the conditional logical operators. This is described
further in Section 7.11.2.
From MSDN C# Conditional Operators
The && and || operators are known as "shortcut short-circuit operators"; the second half is only evaluated if necessary. This is useful for two reasons:
It's more efficient during execution since less code is run (not usually much more, but if you're doing IO or something it could be), and
It's convenient for programming since you can use the first half as a precondition to the second half even being evaluated. Such as,
if (myObj != null && myObj.Name == "something")
If both halves were evaluated above, you'd get an error from myObj.Name whenever myObj was null.
If you do need both halves of the expression evaluated no matter what, you can use the & or the | operators. I find I rarely do.
MSDN: && Operator (C# Reference)
I am messing around with C# and am making a prototype GUI (with no game attached, just messing around with buttons and button colors). I'm running into an error:
private void temperValue_Load(object sender, EventArgs e)
{
int temperInt = 23;
temperInt = Convert.ToInt32(temperValue.Text);
if (temperInt >= 70)
{
temperButton.BackColor = System.Drawing.Color.Red;
}
else if (temperInt >= 40 & <= 69)
{
temperButton.BackColor = System.Drawing.Color.DarkOrange;
}
}
On the "else if" line, I have an error from both the "<=" and the "69)". The "<=" error is "Invalid expression term '<='", and the four errors for the "69)" is ") expected", "Invalid expression term ')'", and two "; expected" errors.
There are no variables outside of this snippet of code that are affecting this code. Every variable called is defined inside the snippet.
(For anyone curious, "temper" stands for "Temperature")
You cannot take shortcuts in your boolean conditions like that.
else if (temperInt >= 40 & <= 69)
Must instead be written as:
else if (temperInt >= 40 && temperInt <= 69)
Note that when making boolean comparisons, you usually want to use the double ampersand &&. This causes short-circuiting (only evaluate both sides if the left side succeeds) which is usually what is wanted. And as I said, you need to include the temperInt identifier both times -- you can't say "where some variable is greater than one value and less than another" like in a SQL BETWEEN clause.
Update: Fixed answer per Eric's suggestion.
if (temperInt >= 40 & <= 69) ...
is not valid C#. Computer languages are a little more restrictive than natural languages. You should use:
if (temperInt >= 40 && temperInt <= 69) ...
(you'll notice I'm also using the logical && operator rather than the bitwise & operator - the former is for truth values, the latter usually for bit manipulation, see this answer for details).
There's another alternative, the use of extension methods:
bool IsBetween (this int me, int lower, int upper) {
return (me >= lower) && (me <= upper);
}
if (temperInt.IsBetween (40, 69)) ...
which is closer to natural language, but that's probably overkill for this case.
you probablly meant temperInt >= 40 && temperInt <= 69
else if (temperInt >= 40 & <= 69)
Should be:
else if (temperInt >= 40 && temperInt <= 69)
You need to include the variable in both parts of the statement, and & is a bitwise AND whereas && is a logical AND which is what you want in this case.
There are a few errors in the given code.
else if (temperInt >= 40 & <= 69)
{
temperButton.BackColor = System.Drawing.Color.DarkOrange;
}
This should actually read
else if (temperInt >= 40 && temperInt <= 69)
{
temperButton.BackColor = System.Drawing.Color.DarkOrange;
}
The && is the logical AND operator in C# and not the '&'. Also the LHS part need to be used in all equality comparisons and not chained like your code sample.