1、要求:
輸入:數字金字塔的層數(例如:7)
輸出:數字金字塔
代碼:
import java.util.*;
public class PrintPyramid{
public static void main(String[] args) {
System.out.println("輸入一所需要三角形層數");
int a = new Scanner(System.in).nextInt();
for(int i=1; i<=a; i++) {
for(int j=(a-i)*3-1; j>=0; j--) { //實現每行縮排
System.out.print(" ");
}
for(int j=i; j>=1; j--) { //列印左半部分
if(j<10)System.out.print(" ");
else System.out.print(" ");
System.out.print(j);
}
for(int j=2; j<=i; j++) { //列印右半部分
if(j<10)System.out.print(" ");
else System.out.print(" ");
System.out.print(j);
}
System.out.println("");
}
}
}
2、要求:
輸入:金字塔層數 (例如:7)
輸出:數字金字塔
import java.util.Scanner;
public class PrintPyramid {
public static void main(String[] args) {
int row =new Scanner(System.in).nextInt();
for(int i = 0;i <= row;i++){
//實現每行縮排
for(int k = 0;k < (row - i);k++){
System.out.print(" ");
}
/**
* 左半部分:
* 一位元的話4個空格
* 二位元的話3個空格
* 三位元的話2個空格
*/
for(int j = 0;j <=i;j++){
if(((int)Math.pow(2, j)) < 10){
System.out.print(" ");
}
else if(((int)Math.pow(2, j)) > 99){
System.out.print(" ");
}
else{
System.out.print(" ");
}
System.out.print((int)Math.pow(2,j));
}
//左右縮排
System.out.print(" ");
/**
* 右半部份:
* 類似左半部分
*/
for(int l = i - 1 ;l >= 0;l--){
System.out.print(" " + (int)Math.pow(2, l));
if(((int)Math.pow(2, l)) < 10){
System.out.print(" ");
}
else if(((int)Math.pow(2, l)) > 99){
System.out.print(" ");
}
else{
System.out.print(" ");
}
}
System.out.println();
}
}
}