Pyramid pattern

Pyramid pattern

Problem Description

Print out isosceles pyramid shape.

Algorithm thinking

  • This print graphics, the core is press-line printing => pyramid graphic each row has space and an asterisk composition
  • Find the line number n the number of laws and spaces and an asterisk

The sample code

Python

# 这种打印的就是按行打印

def fun(n):
    """
    :param n: 金字塔的层数
    """
    for line in range(1, n + 1):
        # 打印空格
        for i in range(n - line):
            print(" ", end="")
        # 打印星号
        for i in range(2*line -1):
            print("*",end="")
        print()

fun(5)

Java



import java.util.Scanner;

public class 金字塔图案 {

    // print1(n) => 正三角
    static void print1(int n) {
        // 按行来打印
        for (int i = 1; i <= n; i++) { // 第i行
            // 打印空格
            for (int j = 0; j < n - i; j++) {
                System.out.printf(" ");
            }
            // 打印星号
            for (int j = 0; j < 2 * i - 1; j++) {
                System.out.printf("*");
            }
            System.out.println();
        }
    }

    // print2(n) => 倒三角
    static void print2(int n) {
        // 按行打印
        for (int i = 1; i <= n; i++) {
            // 打印空格
            int nn = i - 1;
            while (nn-- > 0) {
                System.out.printf(" ");
            }
            // 打印星号
            nn = 2 * (n - i) + 1;
            while (nn-- > 0) {
                System.out.printf("*");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        // 1. 找到行数n和空格,星号的关系

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入金字塔层数: ");
        int n = sc.nextInt(); // n => 层数

        print1(n);
        System.out.println();
        print2(n);
    }

}

Guess you like

Origin www.cnblogs.com/Rowry/p/11823832.html