【问题标题】:Recursive C Function - Print Ascending Order递归 C 函数 - 打印升序
【发布时间】:2015-05-18 03:49:34
【问题描述】:

我正在尝试实现一个递归调用自身并按升序打印给定数字的代码,即如果数字为 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。

也不允许有外部全局变量或外部函数!

【问题讨论】:

  • 看看static做了什么

标签: c loops recursion


【解决方案1】:

函数可以通过以下方式简单定义

void print_ascending( unsigned int n )
{

    if ( n > 1 ) print_ascending( n - 1 ); 
    printf( "%u ", n );
}

我使用了unsigned int 类型而不是int,因为否则你必须考虑n 可以是负数的情况。

【讨论】:

    【解决方案2】:

    每次调用递归函数时,尝试增加参数的值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-18
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2022-01-02
      • 2014-04-08
      • 2019-09-09
      • 2016-05-07
      相关资源
      最近更新 更多