2012-01-05 82 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