public void staircase(int n)
{
// I need to retain the value of "n" going forward in my recursion calls
// Also, everything needs to be done inside the method!
int check = 0;
if(n != 0)
{
for (int i = 0;i< n; i++)
{
// method to draw
if (check < (n - 1))
{
Console.Write(" ");
check++;
}
else
Console.Write("#");
}
if (check != 0)
{
Console.Write("n");
staircase(check);
}
}
Console.ReadLine();
}
一种选择是向方法添加第二个参数并将其设置为某个默认值,可能null
(通过使其成为可为空的int
(。然后,仅当它是null
时才将其设置为n
的值(指示这是第一次调用该方法(,以便可以将其传递给后续递归调用:
public void staircase(int number, int? original = null)
{
// On the first iteration, 'original' should be null, so assign 'n' to it
if (original == null) original = number;
// * Other code remains the same *
// Pass 'original' to recursive calls, which should be the first value of 'n'
if (check != 0)
{
Console.Write("n");
staircase(check, original);
}
// * Other code remains the same *
}
您可以使用如下本地方法:
public void StairCase(int n)
{
void StairCaseInner(int n_inner)
{
// you can still access `n` in here.
Console.WriteLine(n);
int check = 0;
if (n_inner != 0)
{
for (int i = 0; i < n_inner; i++)
{
// method to draw
if (check < (n_inner - 1))
{
Console.Write(" ");
check++;
}
else
Console.Write("#");
}
if (check != 0)
{
Console.Write("n");
StairCaseInner(check);
}
}
}
StairCaseInner(n);
Console.ReadLine();
}
当我调用StairCase(5);
时,我从中得到的输出是:
5 # 5 # 5 # 5 # 5 #
我很想知道该方法对原始n
有什么作用。