如何将递归方法转换为while循环 [英] How to convert a recursion method into a while loop

查看:330
本文介绍了如何将递归方法转换为while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有这个方法



私人int recur(int X){

if(X == 0)

返回1;

其他

返回X * recur(X-1);

}



我正在尝试转换为while循环,但它没有相应的工作。以5作为参数我得到不同的答案。



私人int recur(int x){

Hi I have this method

Private int recur(int X){
if (X==0)
return 1;
else
return X*recur(X-1);
}

I'm trying to convert to a while loop but it's not working accordingly. taking 5 as a parameter I get different answers.

Private int recur(int x){

int i = 0; int val=0;
       while(i<X){
           if(X==0)
               val= 1;
           else{
               val+= X*(X-1);
               i++;
           }

        }
       return val;

推荐答案

嗯。

Um.
Private int recur(int X){
if (X==0)
return 1;
else
return X*(X-1);
}



不是递归的......

它总是返回X *(X-1),所以如果你给它是5,它总是返回20,而不是因子(5)或120 ......

你的循环版本也不返回阶乘:使用循环的阶乘版本将是:


Isn't recursive...
It always returns X*(X-1), so if you give it "5", it will always return 20, not Factorial(5) or 120...
And your loop version doesn't return a factorial either: The factorial version using a loop would be:

int val = 1;
while (X > 0)
    {
    val *= X--;
    }


这篇关于如何将递归方法转换为while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆