java奇怪的双返回

时间:2015-11-16 12:57:29

标签: java algorithm

我写了这个函数,但我真的不明白为什么我有这个输出。

功能:

double itr = 1.0;

public double findClosestXupper(double xone, double fxone) {
    double xtwo, fxtwo;
    xtwo = xone + itr;
    fxtwo = xtwo - Math.pow(xtwo, 2);
    if(fxone < 0) {
        if(fxtwo < 0) {
            System.out.println("check1 " + xtwo + "    " + fxtwo);
            xtwo = xone - itr;
            fxtwo = xtwo - Math.pow(xtwo, 2);
            System.out.println("check2 " + xtwo + "    " + fxtwo);
            if(fxtwo < 0) {
                itr = itr + 1.0;
                System.out.println("check3 " + xtwo + "    " + fxtwo);
                findClosestXupper(xone, fxone);
            }
        }
    }
    System.out.println("check4 " + xtwo + "    " + fxtwo);
    return xtwo;
}

输出:(输入xone = 3.2; fxone = 3.2 - 3.2 ^ 2 - 负变量)

check1 4.2    -13.440000000000001
check2 2.2    -2.6400000000000006
check3 2.2    -2.6400000000000006
check1 5.2    -21.840000000000003
check2 1.2000000000000002    -0.2400000000000002
check3 1.2000000000000002    -0.2400000000000002
check1 6.2    -32.24
check2 0.20000000000000018    0.16000000000000011
check4 0.20000000000000018    0.16000000000000011
check4 1.2000000000000002    -0.2400000000000002
check4 2.2    -2.6400000000000006

为什么check4会显示三次? 000000000000002来自哪里? 谢谢!

1 个答案:

答案 0 :(得分:2)

“check4”显示3次的原因是由于findClosestXupper在其自身内被调用了3次。第一次,所有情况都成立,并调用findClosestXupper(xone, fxone);。在第二次调用中,所有情况都再次成立,导致第二次调用findClosestXupper(xone, fxone);。在第三次调用中,情况不成立,并打印'check4',然后第三次调用返回。这导致第二次调用完成其调用并返回其'check4',然后返回并导致第一次调用也完成并返回第一个'check4'。我们看到稍微随意的尾随十进制值的原因是浮点精度。有关详情,可以找到here