+ 1
Zero or More? Explain please.
Hi everyone! So I’ve been doing C# challenge against someone and met this question: What is the output of this code? static void Func(int a) { a%=2 return; } public static void Main(string[] args) { int a = 100; Func(a); Console.Write(a==0 ? “Zero” : “More”); } 100%2=0, so I answered Zero, but it turns out that the right answer is “More”. Is it wrong answer or I’m not that experienced to find a mistake? Someone, explain please.
4 Réponses
+ 5
okay, so maybe the question isn't written well.
and someone can add on or correct me on this response as there might be some nuance that I am missing..... as I am learning also..
As I understand it, the function is void so it does not return a value. a = 100 and still equals 100 even after passed to a function...
to get the statement to be true, you would have to have it return a value and assign it back to the variable.
like so..
static int Func(int a)
{
a %= 2;
return a;
}
static void Main(string[] args)
{
int a = 100;
a = Func(a); // this will set a to zero
Console.Write(a == 0 ? "Zero" : "More");
Console.WriteLine();
}
+ 2
As laura said. Variable is not passed as reference, so value is copied, hence original is unchanged.
+ 1
Wow, that makes sense
0
Also the Func method doesn’t take referans parameter.
If the method were like this, your result could be Zero.
static int Func(out int a)
{
a%=2;
return;
}