gpt4 book ai didi

java - 我需要帮助用嵌套的 for 循环制作这个形状 [更新]

转载 作者:行者123 更新时间:2023-11-29 05:15:54 25 4
gpt4 key购买 nike

我需要使用嵌套的 for 循环打印出这个形状作为家庭作业(完全披露。)我无法弄清楚如何将整个事物居中。

enter image description here

句点代表该模式的延续。所以它应该是整个金字塔。

这就是我现在

所拥有的
    public static void question4(){

int ix = 30;
for(int i = 1; i<=128; i=i*2){

// x is the number printed
//it gets the value from i,
for (int g = ix; g>=0; g--){
System.out.print(" ");
}
for (int x2 =1; x2<=i-1; x2=x2*2){

System.out.print(" ");
System.out.print(x2);

}
for (int x = i; x>=1; x=x/2){
System.out.print(" ");
System.out.print(x);

}

ix=ix-4;
System.out.println();

感谢您在递减空格方面的帮助,但是现在数字本身会推倒底部的行。我尝试使用另一个用户建议的 string.length 命令,但它一直返回错误。

enter image description here

enter image description here

最佳答案

尝试这样的事情:

public static void main(String[] args) {
String spacer = " ";
for (int i = 1; i <= 128; i = i * 2) {

// x is the number printed
// it gets the value from i,
System.out.print(spacer);
for (int x2 = 1; x2 <= i - 1; x2 = x2 * 2) {
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x >= 1; x = x / 2) {
System.out.print(" ");
System.out.print(x);
}
if ((i * 2) < 10)
spacer = spacer.substring(0, spacer.length() - 2);
else if ((i * 2) < 100)
spacer = spacer.substring(0, spacer.length() - 3);
else
spacer = spacer.substring(0, spacer.length() - 4);
System.out.println();
}
}

这将为每行创建空间,随着您沿着三角形向下移动,空间会减少。

给出这个输出:

                      1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

关于java - 我需要帮助用嵌套的 for 循环制作这个形状 [更新],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26555379/

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