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

关于c - C 语言递归金字塔星形图案程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43726810/

相关文章:

c - 我如何获得此readdir代码示例以搜索其他目录

c - 打印最长的输入行。(K&R(2e)(第 1.9 节)中的示例)

javascript - 我可以保存一个文件,该文件将仅使用 javascript/C/C++ 在服务器端从 php 代码生成,并且没有打开浏览器吗?

c - pthread_create segfault(缓冲读取器示例)

c - 如何将 SSE 应用于长度不能保证为 4 的倍数的数组?

c - 删除 BST 中的节点

java - 文件传输后无输入传输 - Socket

c - 指向结构的嵌套指针包含指向包含结构的指针?

c++ - 在 R 中通过引用调用将 C 数组指针转换为 Rcpp

c - 如何在双向链表中实现 "prev"指针逻辑