資源限制
時間限制:1.0s 內存限制:256.0MB
請編程輸出一個菱形。輸入爲菱形中心到頂點的距離
樣例輸入
2
樣例輸出
*
***
*****
***
*
思路:把上半部分解決,倒序輸出下半部分即可。核心內容就是,它怎麼取空格數,怎麼得出每行的*號數,這樣再去理解會好很多。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n + 1; i++) { // 上半部分,正序
for (int j = 0; j < n - i; j++) { // 枚舉控制空格個數
System.out.print(" ");
}
for (int j = 0; j < (i + 1) * 2 - 1; j++) { // (層數+1)*2-1 枚舉每行*號
System.out.print("*");
}
System.out.println(); // 換行
}
for (int i = 0; i < n + 1; i++) { // 下半部分,倒序
for (int j = 0; j < i + 1; j++) { // 層數+1
System.out.print(" ");
}
for (int j = 0; j < (n - i) * 2 - 1; j++) { // (輸入層數-層數)*2-1 倒序輸出
System.out.print("*");
}
System.out.println(); // 換行
}
}
}