-3
如何用C语言中的递归函数在.txt文件中编写恒星金字塔? 例如,对于5行的三角金字塔星星图案程序的输出应该是:用C递推金字塔星图案程序
*
***
*****
*******
*********
我做的非递归:
#include <stdio.h>
int main(void){
int i, space, rows, star = 0;
printf("Enter the number of rows\n");
scanf("%d", &rows);
//printing one row in every iteration
for(i = 1; i <= rows; i++){
/* Printing spaces */
for(space = 1; space <= rows - i; space++){
printf(" ");
}
//Printing stars
while(star != (2 * i - 1)){
printf("*");
star++;
}
star = 0;
//move to next row
printf("\n");
}
return 0;
}
不能excatly弄清楚递归。
void print_pattern(int spaces, int stars){
static int spaces = 4, stars = 1, number_of_lines = 5;
int i, j;
for(i = 1; i <= spaces; i++)
printf(" "); //print spaces
for(j = 1; j <= stars; j++)
printf("*"); //print stars
if(number_of_lines > 0){
number_of_lines -= 1;
//call recursively if all lines are not printed
print_pattern(spaces - 1, stars + 1);
}
}
你尝试过什么做的? – UnholySheep
想想这个问题,并尝试解决它,然后张贴你卡住的地方! –
您可能会尝试编写一个函数,该函数以字符为单位,使用基本宽度和当前宽度。找出如何将当前宽度居中放在基本宽度中并打印出星号。然后,如果当前宽度不等于基本宽度,则递归调用该函数,传递基本宽度和当前宽度加两。玩的开心。 –