How to find multiple in C# - c#

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.

Related

c# code is unity, that I couldn't understand [duplicate]

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;
}

Checking if value is in range fails with "Operator `<=' cannot be applied to operands of type `bool' and `int'" [duplicate]

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();
}

Where(i => i % 2 == 0)

I'm currently learning about PLINQ (Parallel Language Integrated Query) on Visual Studio 2012's C#.
In the one lesson Where(i => i % 2 == 0) was given to me, but I've no idea what it means and the book i'm studying from didn't give any explanation.
Does anyone know what this means?
First hope you know % which is "The % operator computes the remainder after dividing its first operand by its second". Read more about % Operator
if you have a list of numbers
var list = new List<Int32>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = list.Where(i => i%2 == 0);
So the result will have 2,4,6,8 and 10.
Same thing can be written as
var ans = new List<Int32>();
foreach (var an in list)
{
if (an%2 == 0)
ans.Add(an);
}
The query is selecting only even numbers, where division by 2 has no remainder.
The % operator computes the remainder after dividing its first
operand by its second. All numeric types have predefined remainder
operators.
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
lambda expressions are a bit weird at 1st however when you experiment a bit in VS (and its intellisense) you'll get used to it in no time. as soon as you type in "i=>" you declare a range variable of your type of object which implements IEnumerable(<T>) interface. In this case i is one element of your list (or other IEnumerable>> list, dictionary....) to investigate this case you search for even numbers...
Let's say this is the case:
List<int> source = new List<int>() { 1, 2, 3, 4 };
var evenNumbers = source.Where(i => i % 2 == 0);
Where is filtering source and returning only it's even numbers.
Where is a Linq extension method that works on any object implementing the IEnumerable interface (likeList).
i => i % 2 == 0 is a lambda expression. In this case it means that for each item i in source, Where will apply the expression i % 2 == 0.
Where selects the items in source for which the lambda expression is true. In this case, the expression is true when i is an even number.
This is because of the modulo operator %, which returns the remainder of the integer division between two numbers a and b: a % b. If a = 4 and b = 3, then a % b values 1, because it is what remains when dividing 4 by 3. If % returns 0, then it means that a is divided by b. If b is 2, then it means that a is even.
Where(i => i % 2 == 0)
it means i goes to where i % 2 == 0 that is if
you are doing it for a list of integer it will return all even numbers from list

list.Sort ArgumentException error: IComparer doesn't not return 0(null)

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.

Return if a given int is an exponent of 2 C#

Given a method of the bool data type that takes in an int variable, what is a single line of code that would determine if the int is an exponent of 2 or 2^n.....2,4,8,16,32 etc. I know of a way using a while loop and if statements, but I'm looking for it to be on one line.
From Bit Twiddling Hacks:
uint v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v != 0) && ((v & (v - 1)) == 0);
Just check if the log (base 2) of the number is an integer.
In one line of C#:
Math.Log(x, 2) % 1 == 0
Bitwise operations are more fun, but lord have mercy on whomever has to maintain that code.
bool powerOfTwo = (unchecked(n & (n-1)) == 0) && (n != 0)
bool answer = ((n & ~(n-1)) == n && n!=0);
This passes all the basic tests I threw at it.
It seems good.

Categories

Resources