日期:2014-05-20  浏览次数:20883 次

递归的实现过程咋写?
比如计算从1到200用递归计算怎么写?

int result = 0;

public static void main(String[] args) {

test t = new test();
System.out.println(t.digui(1));

}

public int digui(int number) {
result = result + number;
number++;
while (number <= 200) {
digui(number);
System.out.println(result);
}
return result;
}


咋一直死循环?

------解决方案--------------------
Java code

public class Test07 {
    int result = 0;

    public void digui(int number) {
        if (number > 200) {
            return;
        }

        result += number;
        digui(number + 1);
    }

    public static void main(String[] args) {
        Test07 t = new Test07();
        t.digui(0);
        System.out.println(t.result);
    }
}

------解决方案--------------------
lz改成:
int result = 0;

public static void main(String[] args) {

test t = new test();
System.out.println(t.digui(1));

}

public int digui(int number) {
result = result + number;
number++;
if (number <= 200) {
digui(number);
System.out.println(result);
}
return result;
}

就不会死循环了


------解决方案--------------------
从1到200什么?求和还是阶乘还是。。。
问题都没描述清楚

Java code
public static void main(String[] args) {

    test t = new test();
    System.out.println(t.digui(200));

}

public int digui(int number) { //递归求和
    if (number <= 1) return number;
    return number + digui(number-1);
}

------解决方案--------------------
参考下:

Java code

    int digui(int n)
    {
        if(n==0)
        {
            return n;
        }
        else
        {
            return n+digui(n-1);
        }
    }

------解决方案--------------------
Java code
number++;
        while (number <= 5) {
            digui(number);
            System.out.println(result);
        }

------解决方案--------------------
这是我帮你改过的
[code=Java][/code]
public class Test1{
int result = 0;
public static void main(String[] args) {
Test1 t = new Test1();
t.digui(1);
}

public void digui(int number) {
result = result + number;
number++;
if (number <= 20) {
digui(number);
}else
System.out.println(result);
}

}

------解决方案--------------------
Java code

public class Test {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.digui(200));
    }

    public int digui(int number) {
        if(number == 1){
            return 1;
        }else{
            return number + digui(number - 1);
        }
    }
}