如何使用C中的递归函数在.txt文件中编写星形金字塔?
例如,对于5行的三角形金字塔星形图案,程序的输出应为:

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


我做了非递归的:

#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;
}


无法完全找出递归。

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);
    }
}

最佳答案

如下面的演示程序所示,可以按以下方式编写递归函数。您需要做的就是提供一个文件名,打开文件,然后将指针传递给函数中的文件。在演示程序中,使用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

10-08 00:17