Different results in Java and C are used in recursion=

The following very simple java code has strange output, but the same logic code in C and C has the correct output I try to use JDK 1.7 and JDK 1.3 (relative to JRE), and strange output always exists

public class Test {

    public static int sum=0;

    public static int fun(int n) {

        if (n == 1)
            return 1;
        else
            sum += fun(n - 1);  // this statement leads to weird output
        // { // the following block has right output
        //     int tmp = fun(n - 1);
        //     sum += tmp;
        // }

        return sum;
    }

    public static void main(String[] arg) {
        System.out.print(fun(5));
    }
}

Output is 1, should be 8 The relative C / C + + code is as follows:

#include<stdio.h>
int sum=0;
int fun(int n) {

        if (n == 1)
            return 1;
        else
            sum += fun(n - 1);

        return sum;
    }

int main()
{
    printf("%d",fun(5));

    return 0;
}

Add test Java code:

class A {
    public int sum = 0;

    public int fun(int n) {
        if(n == 1) {
            return 1;
        } else {
            sum += fun(n - 1);
            return sum;
        }
    }
}

public class Test {
    public static void main(String arg[]){
        A a = new A();
        System.out.print(a.fun(5));
    }
}

Solution

In order to give a complete answer, I will have fun through this (3) For those who are not interested, why this applies to C but not Java, please ignore my answer

Here's what Java is doing:

Inner pleasure (3)

sum += sum + fn(n-1) // sum is 0

change

sum = 0 + fun(2) // sum is 0

Inner fun (2)

sum = 0 + fun(1) // sum is 0

Inner fun (1)

return 1 // sum is 0

Fun back inside (2)

sum = 0 + 1; // sum is 0

change

sum = 1; // sum will soon become 1

Back inside for fun (3)

sum = 0 + 1; // sum is 1

change

sum = 1; // sum gets reset to 1

This is what C is doing:

Inner pleasure (3)

sum += fn(n-1) // sum is 0

change

sum = sum + fn(2) // sum is 0

Inner fun (2)

sum = sum + fn(1) // sum is 0

Inner fun (1)

return 1 // sum is 0

Fun back inside (2)

sum = sum + 1 // sum is 0

change

sum = 0 + 1 => sum = 1 // sum will soon become 1

Back inside for fun (3)

sum = sum + 1 // sum is 1

change

sum = 1 + 1 // sum will soon become 2

What you should do: I don't know why C evaluates sum after a function call rather than before I don't know if it meets the specifications But I do know that you should not rely on it in any language A correct solution is:

int fun(int n) {
    if (n == 1)
        return 1;
    else
        return n + f(n - 1);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>