输出不打印一切?

时间:2014-09-25 05:41:39

标签: java methods printing output call

试图查看我的程序有什么问题。我不知道为什么输出不是一直打印,因为每个方法都是相同的,只是名称不同。它在接近结束的某个点之后停止,但是代码有更多的东西。

public static void main(String[] args)
{       
    //x^3 + x^2 + 1
    //2x^3 - 2x^2 - 2
    //3x^3 + 3x^2 + 3

    newrap1();
    newrap2();
    newrap3();
}
public static double func1(double x)
    {
        double f1;
        f1 = Math.pow(x, 3) + Math.pow(x, 2) + 1;
        return f1;
    }
public static double func2(double x)
    {
        double f2;
        f2 = 2*Math.pow(x, 3) - 2*Math.pow(x, 2) - 2;
        return f2;
    }
public static double func3(double x)
    {
        double f3;
        f3 = 3*Math.pow(x, 3) + 3*Math.pow(x, 2) + 3;
        return f3;
    }
public static double der1(double x)
    {
        double d1;
        d1 = 3*Math.pow(x, 2) + 2*x;
        return d1;
    }
public static double der2(double x)
    {
        double d2;
        d2 = 6*Math.pow(x, 2) - 4*x;
        return d2;
    }
public static double der3(double x)
    {
        double d3;
        d3 = 9*Math.pow(x, 2) + 6*x;
        return d3;
    }
public static void newrap1()
    {
        double x = 100;
        for (int i = 0; i < 30; i++)
        {
            double diff;
            diff = func1(x)/der1(x);
            if (diff == 0) return;
            x -= diff;
            System.out.println(Math.floor(x * 1e6) / 1e6);

        }
        System.out.println("The root is -1.465572 after 20 iterations.");
        System.out.println();
    }
public static void newrap2()
    {
        double x = 100;
        for (int i = 0; i < 30; i++)
        {
            double diff;
            diff = func2(x)/der2(x);
            if (diff == 0) return;
            x -= diff;
            System.out.println(Math.floor(x * 1e6) / 1e6);
        }
        System.out.println("The root is 1.465571 after 15 iterations.");
        System.out.println();
    }
public static void newrap3()
    {
        double x = 100;
        for (int i = 0; i < 30; i++)
        {
            double diff;
            diff = func3(x)/der3(x);
            if (diff == 0) return;
            x -= diff;
            System.out.println(Math.floor(x * 1e6) / 1e6);
        }
        System.out.println("The root is -1.465572 after 20 iterations.");
        System.out.println();
    }   

2 个答案:

答案 0 :(得分:0)

newrap3()方法中,变量diff等于零,因此方法返回而不打印输出的其余部分。

        diff = func3(x) / der3(x);
        if (diff == 0) {
            return;
        }

也许不是返回,你会想要一个break,如下:

        if (diff == 0) {
            break;
        }

答案 1 :(得分:0)

newrap3() i=22 x-1.4655712318767682的值为func3(-1.4655712318767682)

致电0将返回diff = func3(x)/der3(x);,因此0也将if (diff == 0) return;

然后newrap3()将退出{{1}},然后才能在方法底部找到2个打印语句。