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;
Related
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;
}
I wanted to figure out a way to make my floating points move and change faster than the typical x++ so I decided to add more of those increments into the same while loop so they stack
While (True)
{
x++;
x++;
x++;
x++;
}
The functionality works but how do i do this with shorter code?
You can replace that with:
while (...)
{
x += 4;
}
This represents x = x + 4
You can also do this with subtraction, multiplication, and division, respectively -=, *=, and /=. Read more here
x += 4; // Adds 4 to x, and stores the result in x.
Try += operator:
x+=4;
in this way x will be incremented by 4.
What does this expression actually mean??
Note - the x and y vars are just sample values.
int x = 3;
int y = 1;
if ((x & y) !=0)
I inherited a codebase and am not up to speed on bitwise operators. I have read up, but am still missing something. Help!
It's comparing the bits in each value. It returns any bits that are set in both numbers.
In your example:
3: 0011
1: 0001
3 & 1: 0001
This checks whether x and y both have at least one common bit set. In the case of your example this would be the true.
if ((x & y) != 0)
This would typically be used to determine whether the value x has a specific bit-flag (y) set. The AND operator returns an integer with only those bits set that are set in both operands.
i have the following problem and I cannot figure out where it comes from. I would appreciate help very much.
The code:
List<Point> lst = new List<Point>();
lst.Add(new Point(0, -2));
lst.Add(new Point(-1, -2));
lst.Sort(delegate (Point x,Point y)
{
if (x.X == 0)
return -1;
else if (y.X == 0)
return 1;
else
{
double retVal1 = x.Y * 1.0 / -x.X;
double retVal2 = y.Y * 1.0 / -y.X;
int retVal = -Math.Sign(retVal1 - retVal2);
return retVal;
}
});
If executed, I recieve an ArgumentException saying that IComparer doesn't not return 0(null). However, it actually cannot return anything else but -1, 0 and 1, or?
Thank you very much for your help!
Ah, btw i'm using .NET 3.5
Actually the error message says: IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x). x: '' x's type: 'Point' The IComparer: 'System.Array+FunctorComparer`1[System.Drawing.Point]'.
You must return 0 if the objects are identical:
lst.Sort(delegate(Point x, Point y) {
if (x.X == y.X && x.Y == y.Y) { // you are missing this
return 0;
}
if (x.X == 0)
return -1;
else if (y.X == 0)
return 1;
else {
double retVal1 = x.Y * 1.0 / -x.X;
double retVal2 = y.Y * 1.0 / -y.X;
int retVal = -Math.Sign(retVal1 - retVal2);
return retVal;
}
});
You haven't completely read the Exception-Message. It most likely says that it does not return 0 for the same instance of the object.
Your code is wrong, if the same instance of Point or an identical value is passed in, it needs to return 0. Otherwise he would never know when he's done with sorting and would end up in an endless loop...and we all know that this is an absolute negative performance hit.
As said, a comparer must return 0 for the the same value as identity entails equality (something is always equal to itself) and equality entails equivalence (you may order two different things equivalently, but you must order two equal things equivalently).
There is a further problem, in that your check for .X being 0 could result in the same items returning inconsistent ordering if they both have .X equal to 0. It's an important rule that a comparison method must always be consistent in that:
If x < y then y > x.
If x < y and y < z then x < z.
Your algorithm breaks the first rule as thus:
Say point a is {0, 3} and point b is {0, 2}
Calling with (a, b) then returns -1 meaning a < b, but calling with (b, a) returns -1 meaning b < a.
Replace the whole thing with:
lst.Sort(delegate (Point x,Point y)
{
return (x.Y * 1.0 / -x.X).CompareTo(y.Y * 1.0 / -y.X);
});
(Note that this implicitly returns 0 for equal points - we could add an explicit check if this was a heavier calculation as an optimisation, but it isn't necessary.
Also, is Point here System.Drawing.Point? If so then this code is now fine, but if it's something else then it's worth noting that the code is fine if Point is a struct, but should contain a null check if Point is a class.
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.