This question already has answers here:
How do I use the conditional (ternary) operator?
(10 answers)
Closed 10 months ago.
I really need someone to explain this part of code float x = Random.Range(0,2) == 0 ? -1 : 1; I understand that it generates a random value of either 1 and -1, and that this float x = Random.Range(0,2) give x a value between 0 and 2, but what does this == 0 ? -1 : 1; do, and how does it function?
This is the conditional operator
The code is equivalent with:
float r = Random.Range(0,2);
float x;
if (r == 0)
x = -1;
else
x = 1;
With the conditional operator x can be initialized while with the equivalent if code I show x must be assigned after initialization. This doesn't matter for float but for other types it may matter.
As you said Random.Range(0,2) gives a value between 0 and 2. The question mark in this variable assignment is called a ternary operator and works like this: condition ? assign this value if true : assign this value if false.
So in your case if it equals 0, x will be set to -1, if it does not it will equal 1
You can find out more here, at the official Microsoft docs
A question mark and colon in this circumstance is an inline if statement using the “ternary conditional operator”.
It acts similarly to an if statement but within a larger statement on a single line. For example this:
if( a > b )
largest = a;
else
largest = b;
Is equivalent to:
largest = ( a > b ? a : b );
If the conditional statement before the ? is true, the whole clause will become the value immediately after the question mark. If the conditional statement before the ? is false, the whole clause will become the value immediately after the colon (:).
You can use more than one of them in a line, for example:
bool a = false;
int i = 3;
Console.WriteLine(“a is “ + ( a ? “true” : “not true” ) + “ and i is “ + ( i == 3 ? “three” : “not three” ) + “!”);
Note that the “else” is not optional.
So in effect the code you posted is saying “if the random number == 0, x=-1, else x=1”.
It is ternary operator, it is similar to if else condition.
For example if you write var x = random == 0 ? -1 : 1; then in terms of if else condition it will be
if(random == 0)
{
x = -1;
}
else
{
x = 1;
}
Related
This question already has answers here:
How to elegantly check if a number is within a range?
(33 answers)
Closed 1 year ago.
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?
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")
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();
}
This question already has answers here:
Behaviour and Order of evaluation in C# [duplicate]
(2 answers)
Closed 2 years ago.
As a beginner, I had difficulty understanding the code below.
I expected the a increments twice and the result will be 2 but it isn't.
var a = 0;
a += ++a;
Console.WriteLine(a); // 1
It seems like one value is dropped. How to understand that?
Well, a += n is equivalent to a = a + n
a += ++a; is therefore equivalent to a = a + ++a;
In turn, this is equivalent to a = a + (a + 1);
Substituting your value of a, we get a = 0 + (0 + 1);
Remember that operands in an expression are evaluated from left to right. Eric Lippert goes into evaluation order in depth here.
What does this mean in practice?
Well, if we write a = a + ++a;, a will become 1 because the first a is 0 at the time of evaluation, and then becomes 1 in ++a, meaning the overall assignment is a value of 1.
If we reverse this a little and instead write a = ++a + a; then ++a will calculate 1, and by the time we reach the second a, it's already 1, meaning that we effectively have a = 1 + 1; so we get 2.
You can verify that with the following code:
var a = 0;
a = a + ++a;
var b = 0;
b = ++b + b;
Console.WriteLine(a); // 1
Console.WriteLine(b); // 2
Try it online
I understand standard usage of ternary operator..
string message = hasError=="Y" ? "There's an error!" : "Everything seems fine...";
But how do I add an OR in the subexpression..
if((hasError=="Y")||(seemsfine=="N")){
message="There's an error!";
}else{message="Everything seems fine...";
}
Any help is sincerely appreciated
Thanks
You can do it like this
string message = hasError == "Y" || seemsfine == "N" ? "There's an error!" : "Everything seems fine...";
There is not much difference. This is because the ternary operator in C# is that handy!
Ultimately, it is the result of the whole expression (that is, hasError == "Y" || seemsfine == "N") that matters, not how many conditions you have. You can put all other conditions if you want too, as long as the whole expression return true then it will assign the first element (left of :) to the variable and when the whole expression is false it assigns the second element (right of :) to the variable
Ternary operator is completely equivalent with if-else statement whose block is simply to assign value to single variable.
Thus,
if (a1 == 0 || a2 > 5 || a3 <= -7)
b = 1;
else
b = 2;
is completely equivalent to
b = a1 == 0 || a2 > 5 || a3 <= -7 ? 1 : 2; //note that there is no bracket here, but it is equivalent to if-else statement with bracket
When you have more than single variable to be assigned, then the equivalent breaks.
if (a1 >= 0)
b = 2;
else
c = 3; //notice the variable difference, you cannot use ternary operator anymore.
As long as it does not hinder the readability of the code for you, you can even put multiple ternary operators like this
b = a1 > 0 && a2 < 0 ? 1 : (a3 < 5 ? 2 : 3);
which is equivalent to
if (a1 > 0 && a2 < 0)
b = 1;
else if (a3 < 5)
b = 2;
else
b = 3;
The initial expression can be as simple or as complicated as you need it to be, as long as the condition ultimately evaluates to a single boolean value, just like the first line of your if statement.
In other words, this:
if ((hasError == "Y") || (seemsfine == "N"))
message="There's an error!";
else
message="Everything seems fine...";
Is equivalent to this:
string message = (hasError == "Y" || seemsfine == "N")
? "There's an error!"
: "Everything seems fine...";
While I´m trying to understand a C# codeblock, I´m asking myself what does this code means:
y -= y > 9 ? 9:0;
Thanks in advance
Yes this bit of code is a bit confusing.
Basically the logic reads like this:
if y is greater than 9
subtract y by 9
otherwise
subtract y by 0
This is also equivalent to the following code:
if (y > 9) {
y = y - 9;
}
else {
y = y - 0;
}
The else case is of course superfluous in this case but I did a literal translation.
For further reading, you can check here. Good luck!
First evaluation:
(y > 9)
If this is true, the expression is evaluated to 9.
If this is false it is evaluated to 0.
This evaluated result is then subtracted from the current value of y.
if y > 9 then subtract 9 from y else subtract zero (do nothing).
It is here as I suppose:
if(y>9)
y=y-9;
else
y=y-0;
This makes use of the ? operator in C#. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression and evaluates as :
if(y>9)
y-= 9;
else
y-= 0;
-= is a subtraction operator.
y -= (expression) means subtract (expression) from y and store that value in y
? : is the ternary operator. It is a way to write an expression that has a conditional value.
(expression) ? x : y means evaluates to x if (expression) is true, and it evaluates to y if (expression) is false
y -= something;
means
y = y - something;
"?" is a ternary operator. Its syntax is:
condition ? true_expression : false_expression
So, the equivalent of that line is:
if (y > 9)
y = y - 9;
else
y = y - 0; // Of course, this wouldn't make sense written like this.
A clear and concise version of that line could be:
if (y > 9)
y -= 9;
how might I find out, in an if statement, weather the specified int is a multiple of 5? This is what I mean:
if(X [is a multiple of] 5)
{
Console.Writeline("Yes");
}
What would be [is a multiple of]?
Also, why is it that when I do:
if(X = 5)
{
Console.Writeline("sdjfdslf");
}
it shows "X = 5" in red and tells me "Can not implicitly convert type "int" to "bool"? I am using X as an input.
how might I find out, in an if statement, weather the specified int is a multiple of 5?
You want to use the modulo operation (%).
if (X % 5 == 0) {
Console.Writeline("Yes");
}
it shows "X = 5" in red and tells me "Can not implicitly convert type "int" to "bool"? I am using X as an input.
The single equals = is assignment. You want the double equals == to do a check for equality.
if (x % 5 == 0) Console.WriteLine("yes");
C# mod operator
Also use == to return a boolean value for a comparison.
You can use the modulus operator (%), which returns the remainder after division:
if (X % 5 == 0) { Console.Writeline("Yes"); }
You're looking for the modulo operator (%) to determine if an integer is a multiple of another integer, like so:
if (x % 5 == 0)
To answer the second part of your question (if (x = 5)), a single equals sign is an assignment operator in C#. You should be using the double equals sign instead, which is the comparison operator, like so: if (x == 5).
= is the assignment operator, while == is used for comparison.
So when your write if (X = 5), you're assigning 5 to X and treat that as a boolean expression.
Interestingly, assigning a value to a variable also returns the value itself.
y = x = 5
assigns 5 to x and assigns the result of (x = 5), which is also 5, to y.