C语言中带递归的金字塔星型程序

C语言中带递归的金字塔星型程序,c,C,如何使用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);

如何使用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;
}

想一想问题,试着解决它,然后把你遇到的问题贴出来!!您可以尝试编写一个以字符为单位的基宽度和以字符为单位的当前宽度的函数。找出如何将当前宽度居中于基准宽度,并打印出相应数量的星号。然后,如果当前宽度不等于基准宽度,则递归调用该函数,传入基准宽度和当前宽度加上2。玩得开心。1 void functionnum;->functionnum;,void funknum;->functionnum;,dat->f2 f=fopenpyramid.txt,w;不要每次函数调用都打开文件,根据w模式,上一个文件的内容将丢失。我在main函数的定义中调用fopen。
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