【问题标题】:Value of variable on recursive calling of a function递归调用函数时的变量值
【发布时间】:2016-07-23 03:47:37
【问题描述】:

考虑函数

void solve(int arr[],int ind,int sum,int n,int count)
{
    if(ind==n){
          if(sum>max)
              max=sum;
      }
      else{
          sum+=arr[ind];//sum
          if(ind==n-1)
            solve(arr,ind+1,sum,n,1);//1st call
          if(ind==n-2 && count>1)
            solve(arr,ind+2,sum,n,1);//2nd call
          if(ind<n-1 && count<2){
              count++;
              solve(arr,ind+1,sum,n,count);//3rd call
          }
          if(ind<n-2)
              solve(arr,ind+2,sum,n,1);//4th call
          if(ind<n-3)
              solve(arr,ind+3,sum,n,1);//5th call
      }
}

我对逻辑没有问题,但对变量的传递感到困惑。我无法确定整数 sum+=arr[ind] //sum 是在每次调用中作为同一个变量传递,还是在每次调用后更新函数?

【问题讨论】:

  • Thnx ..我得到了我猜想的答案...但是@user3386109 你所说的 c++ 答案是什么意思....在 c 中有什么不同吗?
  • 引用是一个 C++ 特性。在 C 中,您将使用指针。

标签: c++ c function parameter-passing


【解决方案1】:

sum 是按值传递的,所以不会更新值。以下 5 个 solve 调用将以相同的 sum 值传递。

如果您希望在每次调用后更新sum,您应该通过引用传递它:void solve(int arr[],int ind,int &amp;sum,int n,int count)

【讨论】:

    【解决方案2】:

    sum 的值会更新,但每次调用函数 solve 时都会更新 locally。您可以通过在函数定义中打印 sum 的值来可视化这一点。

    请看下面的例子。

    #include <stdio.h>
    void call(int);
    int main(void) {
        // your code goes here
        call(5);
        return 0;
    }
    void call(int sum)
    {
        if(sum>15)
          return;
        printf("%d ",sum);
        sum+=5;
        call(sum);
    
    }
    

    o/p 是5 10 15

    这可能有助于您更清晰地形象化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 2020-07-08
      • 1970-01-01
      • 2019-12-06
      相关资源
      最近更新 更多