以下是一个使用 Java 代码实现金字塔形杨辉三角的示例:

import java.util.Scanner;

public class YangHuiTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print('请输入杨辉三角的行数:');
        int numRows = scanner.nextInt();
        
        int[][] triangle = new int[numRows][];
        
        for (int i = 0; i < numRows; i++) {
            triangle[i] = new int[i + 1];
            triangle[i][0] = 1;
            triangle[i][i] = 1;
            
            for (int j = 1; j < i; j++) {
                triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
            }
        }
        
        for (int i = 0; i < numRows; i++) {
            for (int k = 0; k < numRows - i - 1; k++) {
                System.out.print(' ');
            }
            
            for (int j = 0; j <= i; j++) {
                System.out.print(triangle[i][j] + ' ');
            }
            
            System.out.println();
        }
    }
}

输入 6 后,程序将打印出一个金字塔形的杨辉三角形:

     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 
1 5 10 10 5 1 

希望这次的输出符合您的期望!如果还有其他问题,请随时告诉我。


原文地址: https://www.cveoy.top/t/topic/baKM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录