0
Explain.
static int Pow(int x, int y=2) { int result = 1; for (int i = 0; i < y; i++) { result *= x; } return result; } static void Main(string[] args) { Console.WriteLine(Pow(6));// Why is this equal to 36 //Outputs 36 Console.WriteLine(Pow(3, 4));//Why is this equal to 81 //Outputs 81 }
4 ответов
+ 8
6*6=36
3*3*3*3=81
+ 1
Console.WriteLine(Pow(6)); // sets x=6 y stays the same meaning 2
int result=1; //result is set to 1
for (int i=0; i < y; i++) //this asks if i is smaller then y, meaning 0<2 which is true thus it increments i by 1 because of i++ and i=1
result *= x; //means result=result * x which means result=1 * 6 thus result is now 6
since this is a loop which has not ended it goes back to
for (int i = 0; i < y; i++) but this time (int i = 1; 1 <2; i++)// i is still smaller then y therefore it increments i by 1 again and it becomes 2
result *= x; // since result is now 6 instead of 1 you get result=result * x turns into
result=6 * 6=36
for (int i = 0; i < y; i++) this loop can no longer run since i=2 now and 2<2 in ends it so it skips to return result; which gives the result 36
The same principle applies to Console.WriteLine(Pow(3, 4)) but this time it also changes y which is no longer 2 but 4
Hope this explains it for you.
+ 1
What does x equal to in result*= x;
+ 1
What does x equal to in result*= x;
result*= x; // This is basically and assignment operator meaning it's just a shorter way of writing result = result * x;
What you are interested here is the result and not x.
x is already stated in the Console.WriteLine
Console.WriteLine(Pow(6)); //This sets x to 6 and y stays the stated default of 2.
Console.WriteLine(Pow(3, 4)); // This sets x to 3 and y changes to 4 overwriting the default 2.
The default is stated at the beginning of the program with:
static int Pow(int x, int y=2)// x is unknown and y is 2 unless stated otherwise.
Hope this explains it for you.