前往
大廳
主題

【C#練習】瞭解methods和for迴圈概念,解讀程式碼的輸出結果

小村 | 2022-11-18 16:46:41 | 巴幣 0 | 人氣 268

●●●Question●●●
What is the output result of the picture?
●●●My Answer●●●
36  
81
●●●My thought●●●
First at all, we need to know the meaning of Pow(6) , Pow(3,4).
We defined the method int Pow(int x, int y=2) and used Pow(6), Pow(3, 4) in our Main part to call the method.
Console.WriteLine(Pow(6)); //we set x=6 and leave y as the default from the first line of code.
Console.WriteLine(Pow(3, 4)); //we set x=3, and this time we overwrite y=4 instead of 2.
With this understanding, we can back to the content of int Power(int x, int y=2) and try to know how the for loop inside the method will execute.
▲Pow(6)condition: we have x = 6 and y = 2 and i which has to be < 2, so our Operator can do its task!
1.First run: i=0, 0 <2
confirmed Result = 1, (result * 6) so do 1 * 6 = 6 <---- New result
2.second run
i++, i = 1, 1 < 2
confirmed new Result = 6, ( Result * 6) so do 6 * 6 = 36 <--- New result
3.third run
i++, i = 2, 2 < 2 Not confirmed! no run
▲Pow(3,4)condition: we have x = 3 and y = 4 and i which has to be < 2, so our Operator can do its task!
1.First run: i=0, 0 < 4
confirmed Result = 1, (result * 3) so do 1 * 3 = 3 <---- New result
2.second run
i++, i = 1, 1 < 4
confirmed Result = 3, (result * 3) so do 3 * 3 = 9 <---- New result
3.third run
i++, i = 2, 2 < 4
confirmed Result = 9, (result * 3) so do 9 * 3 = 27 <---- New result
4.fourth run
i++, i = 3, 3 < 4
confirmed new Result = 27, ( Result * 3) so do 27 * 3 = 81 <--- New result
5.fifth run
i++, i = 4, 4 < 4 Not confirmed! no run

創作回應

相關創作

更多創作