[英]Printing a centered pyramid in Java with ascending and descending numbers
我正在尝试打印2 ^ n的中心金字塔,其中2 ^ row#是每行的中心编号,左边的数字升至2 ^ row#,右边的数字降序。 我是Java的新手,我花了很长时间才得到这么多。 但是现在我被卡住了。 最后一行是唯一正确的行。 我不知道怎么做,所以不是每行都打印64。 任何人都可以给我一个提示吗?
我试过弄乱每个参数-从第一行,最后一行开始最后一个循环,更改启动功率等,但我只是想不通。
谢谢你的任何提示!
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
}
}
你的问题在于你总是以2 ^ 7开始金字塔的右侧,因为你硬编码power2 = 7 decleration和赋值。 如果您在当前行 - 1处启动此值,则会获得您正在寻找的行为。 码:
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = row - 1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
这部分不对。
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
在第2行,您得到power2 = 6,因此显示2 ^ 6 = 64。
你应该做类似的事情
int power2 = power1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
您正在为power2分配常量,而不是依赖于行的值。 你能试试吗?
int power2 =第1行;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.