c++递归函数调用小常识
2021/6/18 11:57:09
本文主要是介绍c++递归函数调用小常识,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1,float和double类型转化在数值很大的时候慎用,比如6423.32563255(double)强制转化float类型时,精确度只能6423.325;应用场景举例:a,b两个double类型,通过求中点求离a小于0.0001的数,在求中点过程中,若有类型转化就会出现无限递归下去
2,我们经常会用到递归函数,但是如果递归深度太大时,往往导致栈溢出。而递归深度往往不太容易把握,所以比较安全一点的做法就是:用循环代替递归,方法如下:
int SomeFuncLoop(int n, int &retIdx) 18 { 19 // (First rule) 20 struct SnapShotStruct { 21 int n; // - parameter input 22 int test; // - local variable that will be used 23 // after returning from the function call 24 // - retIdx can be ignored since it is a reference. 25 int stage; // - Since there is process needed to be done 26 // after recursive call. (Sixth rule) 27 }; 28 // (Second rule) 29 int retVal = 0; // initialize with default returning value 30 // (Third rule) 31 stack<SnapShotStruct> snapshotStack; 32 // (Fourth rule) 33 SnapShotStruct currentSnapshot; 34 currentSnapshot.n= n; // set the value as parameter value 35 currentSnapshot.test=0; // set the value as default value 36 currentSnapshot.stage=0; // set the value as initial stage 37 snapshotStack.push(currentSnapshot); 38 // (Fifth rule) 39 while(!snapshotStack.empty()) 40 { 41 currentSnapshot=snapshotStack.top(); 42 snapshotStack.pop(); 43 // (Sixth rule) 44 switch( currentSnapshot.stage) 45 { 46 case 0: 47 // (Seventh rule) 48 if( currentSnapshot.n>0 ) 49 { 50 // (Tenth rule) 51 currentSnapshot.stage = 1; // - current snapshot need to process after 52 // returning from the recursive call 53 snapshotStack.push(currentSnapshot); // - this MUST pushed into stack before 54 // new snapshot! 55 // Create a new snapshot for calling itself 56 SnapShotStruct newSnapshot; 57 newSnapshot.n= currentSnapshot.n-1; // - give parameter as parameter given 58 // when calling itself 59 // ( SomeFunc(n-1, retIdx) ) 60 newSnapshot.test=0; // - set the value as initial value 61 newSnapshot.stage=0; // - since it will start from the 62 // beginning of the function, 63 // give the initial stage 64 snapshotStack.push(newSnapshot); 65 continue; 66 } 67 ... 68 // (Eighth rule) 69 retVal = 0 ; 70 71 // (Ninth rule) 72 continue; 73 break; 74 case 1: 75 // (Seventh rule) 76 currentSnapshot.test = retVal; 77 currentSnapshot.test--; 78 ... 79 // (Eighth rule) 80 retVal = currentSnapshot.test; 81 // (Ninth rule) 82 continue; 83 break; 84 } 85 } 86 // (Second rule) 87 return retVal; 88 }
这篇关于c++递归函数调用小常识的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-06PingCAP 连续两年入选 Gartner 云数据库管理系统魔力象限“荣誉提及”
- 2025-01-05Easysearch 可搜索快照功能,看这篇就够了
- 2025-01-04BOT+EPC模式在基础设施项目中的应用与优势
- 2025-01-03用LangChain构建会检索和搜索的智能聊天机器人指南
- 2025-01-03图像文字理解,OCR、大模型还是多模态模型?PalliGema2在QLoRA技术上的微调与应用
- 2025-01-03混合搜索:用LanceDB实现语义和关键词结合的搜索技术(应用于实际项目)
- 2025-01-03停止思考数据管道,开始构建数据平台:介绍Analytics Engineering Framework
- 2025-01-03如果 Azure-Samples/aks-store-demo 使用了 Score 会怎样?
- 2025-01-03Apache Flink概述:实时数据处理的利器
- 2025-01-01使用 SVN合并操作时,怎么解决冲突的情况?-icode9专业技术文章分享