递归如何使用堆栈数据结构?

时间:2019-06-25 13:02:23

标签: c++ recursion lifo

我最近读过,递归使用系统堆栈来存储函数调用的返回地址。因此,我只是做了一个随机代码来理解递归中的这个LIFO概念

int fun( int x) 
  {  if ( x<6 || x>6 ) 
       { cout<<x; 
          return 0; 
        } 
      else 
       return max(fun(x-1),fun(x+1)); 
    } 
    int main(){ 
     cout<<fun(6); 
     return 0; 
  } 

我希望输出

570

实际输出为

750

我假设函数将按此顺序调用-

fun(6)->fun(5) { it will print 5 then return 0} ->fun(7) { it print 7 then return 0} -> max(0,0) { return 0}

纠正我,我错了。

1 个答案:

答案 0 :(得分:3)

在C ++中,参数的求值顺序不确定。

编写 Launching lib\main.dart on Redmi Note 5 Pro in debug mode... Initializing gradle... Resolving dependencies... * Error running Gradle: ProcessException: Process "C:\Users\Azhan Khan\AndroidStudioProjects\simple_motivation\android\gradlew.bat" exited abnormally: Starting a Gradle Daemon, 2 busy and 1 stopped Daemons could not be reused, use --status for details FAILURE: Build failed with an exception. * What went wrong: Could not create service of type ScriptPluginFactory using BuildScopeServices.createScriptPluginFactory(). > Could not create service of type ResourceSnapshotterCacheService using GradleUserHomeScopeServices.createResourceSnapshotterCacheService(). * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 1m 23s Command: C:\Users\Azhan Khan\AndroidStudioProjects\simple_motivation\android\gradlew.bat app:properties Finished with error: Please review your Gradle project setup in the android/ folder. 时,编译器可以自由选择首先评估max(fun(x-1),fun(x+1));