gpt4 book ai didi

java - 使用升序和降序数字在 Java 中打印居中金字塔

转载 作者:行者123 更新时间:2023-11-29 06:02:59 25 4
gpt4 key购买 nike

Link to what I want and what I have

我正在尝试打印一个 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 减速和赋值。如果您从当前行开始此值 - 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();
}

关于java - 使用升序和降序数字在 Java 中打印居中金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9455037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com