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

2 回答 2

2

you have to eliminate the "1-" when you define x, i.e. x = ((-1)^(i+1))/i

EDIT

There is no special case for x==1, x is always defined as x=Math.pow(-1,i+1)/i. Note that ((-1)^(1+1))/1 = ((-1)^2)/1 = 1/1 = 1. Also the tal +=x goes in the for-loop.

于 2012-01-05T16:48:24.543 回答
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这里运行它

于 2016-12-06T06:38:19.203 回答