2017-05-01 119 views
-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); 
    } 
} 
+2

你尝试过什么做的? – UnholySheep

+1

想想这个问题,并尝试解决它,然后张贴你卡住的地方! –

+1

您可能会尝试编写一个函数,该函数以字符为单位,使用基本宽度和当前宽度。找出如何将当前宽度居中放在基本宽度中并打印出星号。然后,如果当前宽度不等于基本宽度,则递归调用该函数,传递基本宽度和当前宽度加两。玩的开心。 –

回答

0

递归函数可以按照以下方式编写,如下面的演示程序所示。您只需提供文件名,打开文件并将指针传递给函数中的文件即可。在演示程序中使用stdin作为函数参数。

#include <stdio.h> 
#include <stdbool.h> 

void pyramid(FILE *f, unsigned int n) 
{ 
    static int width = 0; 

    if (n) 
    { 
     ++width; 
     pyramid(f, n - 1); 

     for (unsigned int i = 0; i < 2 * n - 1; i++) 
     { 
      fprintf(f, "%*c", i == 0 ? width : 1, '*'); 
     } 

     fputc('\n', f); 

     --width; 
    } 
} 

int main(void) 
{ 
    while (true) 
    { 
     printf("Enter a non-negative number (0 - exit): "); 

     unsigned int n; 

     if (scanf("%u", &n) != 1 || n == 0) break; 

     putchar('\n'); 

     pyramid(stdout, n); 

     putchar('\n'); 
    } 

    return 0; 
} 

程序输出可能看起来像

Enter a non-negative number (0 - exit): 5 

    * 
    *** 
    ***** 
******* 
********* 

Enter a non-negative number (0 - exit): 4 

    * 
    *** 
***** 
******* 

Enter a non-negative number (0 - exit): 3 

    * 
*** 
***** 

Enter a non-negative number (0 - exit): 2 

* 
*** 

Enter a non-negative number (0 - exit): 1 

* 

Enter a non-negative number (0 - exit): 0