本文介绍了迭代或递归因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 嗨 我用递归的方式实现了阶乘: int factorial( int x){ if (x< = 0 ) return 1 ; else return (x * factorial(x - 1 )); } int _tmain( int argc,_TCHAR * argv []) { std :: cout<< 请输入您的号码:::; int x; std :: cin>> X; std :: cout<< factorial(<< x< < )=<<阶乘(X); getchar();的getchar(); } 实现此类代码的哪种方式更有用,使用迭代和循环编写它或者递归写入如上所述?解决方案 在这种情况下最好使用迭代/循环。 详情请访问: http: //www.informit.com/articles/article.aspx?p=1874865 [ ^ ] 谢谢。 这取决于你的理解通过最好的。它是最快,最容易理解的代码,最优雅,最容易维护等等吗? 如果你必须将其作为库函数实现,速度显然会发挥作用一个重要的角色。那肯定会让你在循环中实现它。递归实现要慢得多,因为每次乘法也会占用过程调用的时间。所以大多数人会说迭代实现是最好的。如果你要编写一个编程类并希望演示递归函数的概念,你的目标可能会有所不同。 你是对的,在这种情况下,递归是最好和最干净的。 / BLOCKQUOTE> HiI've implemented factorial recursively this way:int factorial(int x){if (x <= 0)return 1;elsereturn (x*factorial(x - 1));}int _tmain(int argc, _TCHAR* argv[]){std::cout << "Please enter your number :::";int x;std::cin >> x;std::cout<<"factorial(" << x << ") = "<< factorial(x);getchar(); getchar();}which way of implementing such code is more useful writing it using iteration and loops or writing it recursively such as above? 解决方案 It is better to use Iterations/loops in this case.For details explanation please visit:http://www.informit.com/articles/article.aspx?p=1874865[^]Thanks.It depends on what you understand by "best". Is it fastest, easiest code to comprehend, most elegant, easiest to maintain, etc.?If you had to implement it as a library function the speed would obviously play a big role. And that would certainly have you implement it in a loop. A recursive implementation is much slower, because each multiplication does also consume the time of a procedure call. So most people will say that the iterative implementation is the "best". If you were to give a programming class and wanted to demonstrate the concept of recursive functions your goal could be different, though.You are correct, in this case recursion is best and cleanest. 这篇关于迭代或递归因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-30 02:59