如何使用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);
}
}
答案 0 :(得分: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