java生成给定数字的金字塔?
我想为给定的数字“n”(“n”-也是最后一个金字塔的高度)生成一个金字塔堆栈。算法应该堆叠(n-1)个金字塔。结果应该是这样的:
height of base pyramid: 4
2
2 4 2
2
2 4 2
2 4 8 4 2
2
2 4 2
2 4 8 4 2
2 4 8 16 8 4 2
我已经有了生成最后一个金字塔的代码:
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++)
System.out.printf("%5s", "");
for (k = 1; k < i; k++)
System.out.printf("%5d", (int) Math.pow(2, k));
for (k = i; k >= 1; k--)
System.out.printf("%5d", (int) Math.pow(2, k));
System.out.println();
}
任何想法都会有帮助
# 1 楼答案
在最外层再添加一个
for
循环:-所以,你的循环结构变成:
z
以n - 2
开头,因为第一个金字塔的长度为2。请注意,在第二个内部循环中,您的条件被更改为i <= n - z
现在,您的原始循环集为
n = 4
运行3 times
(n - 2) == 2
,循环从z = 2
运行到z = 0
。它创建了一个高度金字塔(n - z)
:-(4 - 2) = 2
,(4 - 1) = 3
,(4 - 0) = 4
背靠背# 2 楼答案
提示:-
您的代码生成了一个长度为
n
的金字塔将其包含在一个
for
循环中,该循环在counter=n-1
上循环,直到counter=0
在现有代码中替换值。从
n
到n-counter+1