递归 C 函数 - 打印升序
Recursive C Function - Print Ascending Order
我正在尝试实现一个递归调用自身并按升序打印给定数字的代码,即如果数字为 5,则该函数将打印 1 2 3 4 5。我不能在任何循环中使用循环方式!
void print_ascending(int n)
{
int i = 1;
if(i < n)
{
printf("%d", i);
i++;
print_ascending(n);
}
}
当然,这段代码的问题是每次都会将变量i重新初始化为1,并无限循环打印1。
也不允许外部全局变量或外部函数!
每次调用递归函数时,尝试递增参数值。
void print_ascending(int limit, int current_value)
{
if(current_value < limt)
{
printf("%d ", current_value);
print_ascending(limit, current_value + 1);
}
}
最初将函数调用为
print_ascending(5, 1)
或者,
void print_ascending(int n)
{
if(n > 0)
{
print_ascending( n - 1);
printf("%d ", n);
}
}
函数可以简单的定义如下
void print_ascending( unsigned int n )
{
if ( n > 1 ) print_ascending( n - 1 );
printf( "%u ", n );
}
我使用类型 unsigned int
而不是 int
因为否则你必须考虑 n 可以是负数的情况。
我正在尝试实现一个递归调用自身并按升序打印给定数字的代码,即如果数字为 5,则该函数将打印 1 2 3 4 5。我不能在任何循环中使用循环方式!
void print_ascending(int n)
{
int i = 1;
if(i < n)
{
printf("%d", i);
i++;
print_ascending(n);
}
}
当然,这段代码的问题是每次都会将变量i重新初始化为1,并无限循环打印1。
也不允许外部全局变量或外部函数!
每次调用递归函数时,尝试递增参数值。
void print_ascending(int limit, int current_value)
{
if(current_value < limt)
{
printf("%d ", current_value);
print_ascending(limit, current_value + 1);
}
}
最初将函数调用为
print_ascending(5, 1)
或者,
void print_ascending(int n)
{
if(n > 0)
{
print_ascending( n - 1);
printf("%d ", n);
}
}
函数可以简单的定义如下
void print_ascending( unsigned int n )
{
if ( n > 1 ) print_ascending( n - 1 );
printf( "%u ", n );
}
我使用类型 unsigned int
而不是 int
因为否则你必须考虑 n 可以是负数的情况。