how to trace a recursive function C++

前端 未结 2 726
臣服心动
臣服心动 2021-01-20 13:31
#include 
using namespace std;

int g(float A[] , int L , int H)
{
   if (L==H)
      if (A[L] > 0.0)
         return 1;
      else 
         retu         


        
2条回答
  •  心在旅途
    2021-01-20 14:14

    and M = 1 since it its a int -return g(A,0,3) + g(A,2 3)

    Here is first problem. If M = 1, then how do you say it's return g(A,0,3) + g(A,2, 3)?

    It should be:

    return g(A,0,1) + g(A,2, 3)
               //^ this should be 1
    

    And since you're wrong at the first step, all the consecutive steps will be wrong.

    My suggestion would be :

    • Take a pencil and white paper. Be ready to draw a binary tree, that expands downwards
    • Write the root node as g(A,0,3); . This is the first call.
    • Then make two child nodes: left and right
    • Write g(A,0,1) as the left node, and g(A,2,3) as right node.
    • Then again make two child nodes of each child, and keep drawing nodes by repeating this step, till the if condition becomes true.
    • Once the if condition becomes true, stop making new nodes (in that branch), and go up towards the root node, summing the values of nodes which you meet on the way.
    • What you get at the root node, is the return value of original call from main().

提交回复
热议问题