gpt4 book ai didi

java - 我想用Java创建一个 “*”的功率金字塔。

转载 作者:行者123 更新时间:2023-12-01 13:43:31 25 4
gpt4 key购买 nike

输入:基数=2,行=3
输出:

   **
****
********

输入:基=3,行=3
输出:

            ***
*********
***************************

我已经尝试过这种方式,但我的空格打印不正确。

import java.util.Scanner;

public class loops {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();

System.out.println("enter height:");
int h = s.nextInt();


for (int i = 1; i <= h; i++) {

int num = (int)Math.pow(base, i);
for(int n=h-1; n>i-1; n--) {
System.out.print(" ");

}

for (int j = 0; j < num; j++) {
System.out.print("*");
}

System.out.println("");
}
}
}

最佳答案

import java.util.Scanner;

public class loops {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();

System.out.println("enter height:");
int h = s.nextInt();

int spacesNum;
int asterisksNum;

for (int i = 1; i <= h; i++) {

spacesNum = (int) ((Math.pow(base, h) - Math.pow(base, i)) / 2);
asterisksNum = (int) (Math.pow(base, i));

for (int j = 0; j < spacesNum; j++) {
System.out.print(" ");
}

for (int j = 0; j < asterisksNum; j++) {
System.out.print("*");
}

System.out.println();

}

s.close();
}
}

关于java - 我想用Java创建一个 “*”的功率金字塔。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510865/

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