我不理解这种递归的输出。 有人可以帮帮我吗? (流程图肯定会帮助我理解..)
public class Stars {
public static void printNChars (int n, char c) {
for (int j=0; j<n; j++) {
System.out.print(c);
}
}
public static void printNStars (int n) {
printNChars (n, '*');
System.out.println();
}
public static void triangle(int n) {
if (n==1) {
printNStars(1);
}
else {triangle (n-1);
printNStars(n);
}
}
public static void main (String [] args) {
triangle(5);
}
}
public static void main (String [] args) {
triangle(5);
}
}
/ *
* *
* * *
* * * *
* * * * *
答案 0 :(得分:0)
它的工作方式如下:
triangle(n):
triangle(n-1)
printNStars(n)
可以翻译成:
triangle(n)
when previous rows are printed
print nth row.
还有退出规则。如果n为1,则不绘制前一行。只需打印一颗星。
执行将按以下顺序进行:
n = 4:
triangle(4)
triangle(3)
triangle(2)
triangle(1)
printNStars(1)
System.out.println()
printNStars(2)
System.out.println()
printNStars(3)
System.out.println()
printNStars(4)
System.out.println()