-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
想想這個問題,並嘗試解決它,然後張貼你卡住的地方! –
您可能會嘗試編寫一個函數,該函數以字符爲單位,使用基本寬度和當前寬度。找出如何將當前寬度居中放在基本寬度中並打印出星號。然後,如果當前寬度不等於基本寬度,則遞歸調用該函數,傳遞基本寬度和當前寬度加兩。玩的開心。 –