在递归中使用+ =在Java和C ++中有不同的结果 [英] Different results in Java and C++ using += in recursion
问题描述
下面的非常简单的 Java 代码具有奇怪的输出,但 C 和 C ++ 中的相同逻辑代码具有正确的输出。我试着用jdk1.7和jdk1.3(相对jre),奇怪的输出总是存在。我是来自 C 和 C ++ 世界的 Java 新手,现在我疯了。请帮帮我。任何答案将非常感激:
The very simple Java code as follows has the weird output, but the same logic code in C and C++ has the right output. I try with the jdk1.7 and jdk1.3(relative jre), the weird output is always there. I am a newbie in Java from C and C++ world and now I am going crazy. Please help me. Any answer will be highly appreciated:
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));
}
}
输出为1, / C ++代码如下:
The output is 1 which should be 8. 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;
}
添加测试Java代码:
Adding 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));
}
}
推荐答案
I为了给出一个完整的答案,要经历这个乐趣(3)。对于那些不感兴趣的人,为什么这对C ++而言,但不适用于Java,请忽略我的回答。
I'm going to run through this for fun(3) for the sake of giving a complete answer. For those of you who are not interested why this works for C++ but not for Java, please ignore my answer.
这里是Java在做什么: strong>
Here is what Java is doing:
里面fun(3)
sum += sum + fn(n-1) // sum is 0
成为
sum = 0 + fun(2) // sum is 0
then fun(2)
Then inside fun(2)
sum = 0 + fun(1) // sum is 0
然后在fun(1)
return 1 // sum is 0
< 2)
Back inside fun(2)
sum = 0 + 1; // sum is 0
成为
sum = 1; // sum will soon become 1
sum = 0 + 1; // sum is 1
成为
sum = 1; // sum gets reset to 1
C ++正在做什么:
里面fun(3)
sum += fn(n-1) // sum is 0
成为
sum = sum + fn(2) // sum is 0
$ b b
then fun(2)
Then inside fun(2)
sum = sum + fn(1) // sum is 0
然后在里面fun(1)
Then inside fun(1)
return 1 // sum is 0
p>
Back inside fun(2)
sum = sum + 1 // sum is 0
成为
sum = 0 + 1 => sum = 1 // sum will soon become 1
b
$ b
Back inside fun(3)
sum = sum + 1 // sum is 1
成为
sum = 1 + 1 // sum will soon become 2
你应该做什么:
我不知道为什么C ++求值 sum
在调用函数之后,而不是之前。我不知道这是否在规格。但我知道,你不应该依赖于这在任何语言。正确的解决方案是:
What you should do:
I do not know why C++ evaluates sum
after making the function call rather than before. I do not know if this is in the specifications. But I do know that you should not be depending on this in any language. A correct solution would be:
int fun(int n) {
if (n == 1)
return 1;
else
return n + f(n - 1);
}
这篇关于在递归中使用+ =在Java和C ++中有不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!