能否用递归实现横向并排打印多个金字塔?
实现横向并排的递归金字塔打印函数
我正在编写打印金字塔的代码,想要实现一个递归函数,它既能接收金字塔的目标高度参数,也能接收要打印的金字塔数量参数。目前纵向堆叠打印金字塔很容易实现,但我想改成横向并排对齐打印,而不是纵向堆叠。附上我的现有代码,请问能不能创建这样的函数?
piramida (int n,int broj) { int i=0; int y=0; int z=0; int b=1; int c=n; for(i=0;i<n;i++) { for(z=0;z<c-1;z++) { printf(" "); } for(y=0;y<b;y++) { } for(y=0;y<b;y++) { printf("#"); } printf(" "); for(y=0;y<b;y++) { printf("#"); } printf("\n"); b++; c--; } if(broj>0) { piramida(n,broj-1); } else printf(" "); } int main() { piramida(9,2); }
当然可以实现横向并排打印。你的现有代码是每打印完一个完整金字塔就换行纵向堆叠,要改成横向并排,核心思路是按行处理:每一行同时打印所有金字塔的对应行,而不是先打完一个金字塔再打下一个。
递归实现的话,可以调整逻辑,让函数负责打印金字塔的某一行,然后递归处理下一行,直到所有行打印完成;同时在每一行里循环打印指定数量的金字塔的该行内容。
以下是修改后的递归实现代码:
#include <stdio.h> // 打印单个金字塔的某一行 void printPyramidRow(int height, int currentRow) { int spaces = height - currentRow - 1; int hashes = 2 * currentRow + 1; // 打印左侧空格 for (int i = 0; i < spaces; i++) { printf(" "); } // 打印# for (int i = 0; i < hashes; i++) { printf("#"); } // 打印金字塔之间的间隔(这里用2个空格,可根据需求调整) printf(" "); } // 递归打印所有行的横向金字塔 void printHorizontalPyramids(int height, int count, int currentRow) { // 递归终止条件:所有行打印完成 if (currentRow >= height) { return; } // 打印当前行的所有金字塔 for (int i = 0; i < count; i++) { printPyramidRow(height, currentRow); } // 换行到下一行 printf("\n"); // 递归打印下一行 printHorizontalPyramids(height, count, currentRow + 1); } // 对外调用的入口函数 void piramida(int n, int broj) { // 从第0行开始打印 printHorizontalPyramids(n, broj, 0); } int main() { piramida(9, 2); return 0; }
代码说明:
printPyramidRow:负责打印单个金字塔的指定行,包括左侧空格、#,以及金字塔之间的间隔。printHorizontalPyramids:递归函数,每一次调用打印一行的所有金字塔,然后递归处理下一行,直到所有行打印完毕。- 入口函数
piramida初始化递归的起始行(第0行),调用递归函数开始打印。
这样就能实现指定数量的金字塔横向并排对齐打印,而不是纵向堆叠。
内容的提问来源于stack exchange,提问作者20centuryboy
相关产品推荐
相关产品推荐

