java如何打印梯形
打印梯形的实现方法
在Java中打印梯形可以通过嵌套循环实现,关键在于控制空格和星号(或其他字符)的输出比例。以下是两种常见方法:
使用双重循环打印空心梯形
public class PrintTrapezoid {
public static void main(String[] args) {
int rows = 5; // 梯形高度
int base = 10; // 下底长度
for (int i = 0; i < rows; i++) {
// 打印左侧空格
for (int j = 0; j < rows - i - 1; j++) {
System.out.print(" ");
}
// 打印梯形边界
for (int k = 0; k < base - 2*(rows - i - 1); k++) {
if (i == 0 || i == rows - 1 || k == 0 || k == base - 2*(rows - i - 1) - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
打印实心梯形的简化版
public class SolidTrapezoid {
public static void main(String[] args) {
int height = 4;
int topWidth = 3;
int bottomWidth = 7;
for (int i = 0; i < height; i++) {
int currentWidth = topWidth + 2 * i;
int spaces = (bottomWidth - currentWidth) / 2;
for (int j = 0; j < spaces; j++) {
System.out.print(" ");
}
for (int k = 0; k < currentWidth; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
参数化梯形打印方法
更灵活的解决方案是创建一个可配置的方法:
public static void printTrapezoid(int height, int topBase, int bottomBase, char symbol) {
if (bottomBase <= topBase) {
System.out.println("下底必须大于上底");
return;
}
for (int row = 0; row < height; row++) {
int currentWidth = topBase + (bottomBase - topBase) * row / (height - 1);
int padding = (bottomBase - currentWidth) / 2;
// 左侧填充空格
System.out.print(" ".repeat(padding));
// 打印梯形符号
System.out.print(String.valueOf(symbol).repeat(currentWidth));
System.out.println();
}
}
调用示例:
printTrapezoid(5, 3, 9, '#');
数学公式说明
梯形的每行宽度计算遵循线性变化: [ \text{currentWidth} = \text{topBase} + (\text{bottomBase} - \text{topBase}) \times \frac{\text{row}}{\text{height} - 1} ]
其中:

row是当前行号(从0开始)height是梯形总高度topBase和bottomBase分别是上底和下底的长度






