2014-09-25 136 views
0

試圖查看我的程序出了什麼問題。我不知道爲什麼輸出不是一路打印,因爲每種方法都是相同的,只是名稱不同而已。它在結束時的某個點後停止,但代碼更多。輸出不能打印所有內容?

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(); 
    } 
+1

主要方法在哪裏? – 2014-09-25 05:42:46

+0

您是否嘗試過運行調試器來查看它掛起的位置? – 2014-09-25 05:44:17

+0

請提供[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – mkobit 2014-09-25 05:45:16

回答

0

在你newrap3()方法可變diff等於零並且因此該方法返回而不進行打印輸出的其餘部分。

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

的也許不是回報,你想一個break,像這樣:

 if (diff == 0) { 
      break; 
     } 
+0

有線猜測。你如何知道主要方法在這裏使用? – 2014-09-25 05:47:38

+3

@RuchiraGayanRanaweera,我認爲它是開始時的前3個函數調用的主要方法。 – 2014-09-25 05:49:27

+0

在最後的方法中將返回更改爲break可顯示整個輸出。謝謝! – evarias 2014-09-25 06:00:26

0

newrap3()i=22x-1.4655712318767682

調用func3(-1.4655712318767682)將返回0因此diff = func3(x)/der3(x);也將爲0

然後if (diff == 0) return;在到達方法底部的2個打印語句之前將退出newrap3()