2012-01-05 83 views
3

作業:編寫一個方法來計算以下系列: m(i)= 1-(1/2)+(1/3) - (1/4)+(1/5) - 。 .. +((-1)^(I + 1))/ I計算一系列

寫,顯示以下代碼的測試程序:

i:  m(i): 
5  0,78333 
10  0,64563 
..  .. 
45  0,70413 
50  0,68324 

我已經嘗試了幾個小時現在,和我無法想出如何解決這個問題。也許我只是傻哈哈:)

這裏是我到目前爲止的代碼:

package computingaseries; 

public class ComputingASeries { 

    public static void main(String[] args) { 

     System.out.println("i\t\tm(i)"); 
     for (int i = 5; i <= 50; i += 5) { 
      System.out.println(i + "\t\t" + m(i)); 
     } 
    } 

更新:

public static double m(int n) { 
     double tal = 0; 
     double x = 0; 

     for (int i = 1; i <= n; i += 1) { 
      if (i == 1) { 
       x = 1 - ((Math.pow(-1, (i + 1)))/i); 
      } else { 
       x = ((Math.pow(-1, (i + 1)))/i); 
      } 
     } 
     tal += x; 

     return tal; 

    } 
} 

我的錯誤輸出:

i  m(i) 
5  0.2 
10  -0.1 
15  0.06666666666666667 
20  -0.05 
25  0.04 
30  -0.03333333333333333 
35  0.02857142857142857 
40  -0.025 
45  0.022222222222222223 
50  -0.02 
+4

提示這裏運行,^想您所想,不是權力。 – 2012-01-05 16:47:38

+1

此外,整數除法和浮點除法之間的區別是基本的。 – 2012-01-05 16:51:40

+0

Math.pow現在工作,謝謝:)但得到錯誤的輸出:/ – Daniel 2012-01-05 17:13:41

回答

2

你必須在定義x時消除「1-」,即x =((-1)^(i + 1))/ i

EDIT

有對於x == 1無特殊情況下,x爲總是定義爲x = Math.pow(-1,I + 1)/ I。請注意,((-1)^(1 + 1))/ 1 =((-1)^ 2)/ 1 = 1/1 = 1. 另外tal + = x進入for循環。

+1

也是丹W回答是正確的,你必須使用正確的運算符的權力 – Fortunato 2012-01-05 16:53:41

+0

所以我已經消除了「1-」,你告訴我到,現在看起來好嗎? – Daniel 2012-01-05 17:06:30

+0

Math.pow工作,但輸出是完全搞砸了。你能發現問題嗎?更新的代碼@ top :) – Daniel 2012-01-05 17:14:09

0
public class SpecialSeries { 

    public static double m(int n){ 
     double sum = 0; 
     for (int i = 1; i <= n; i++) { 
      sum += Math.pow(-1, (i+1))/(double)i; 
     } 
     System.out.println(n+"\t"+sum); 
     return sum; 
    } 

    public static void main(String[] args) { 
     System.out.println("i:\tm(i)"); 
     for (int i = 5; i < 50; i+=5) { 
      m(i); 
     } 
    } 
} 

你可以在ideone