计算1-1/3+1/5-1/7+1/9-1/11.......+1/21的值

方法一:
package
com.Summer_0424.cn; /** * @author Summer * 计算1-1/3+1/5-1/7+1/9-1/11.......+1/21 */ public class Test09 { public static void main(String[] args) { double sum = 0.0; int op = 1;//作为符号变化的参数,每循环一次,符号变化一次 for (int i = 1; i <= 21; i+=2) { sum = sum + (1.0/i*op);//因为i为整数,计算结果为整数,所以用1.0 op = -op; } System.out.println(sum); } }

方法二:

package com.Summer_0424.cn;

public class Test05 {

    public static void main(String[] args) {
        double sum1 = 0.0;
        double sum2 = 0.0;
    
        for (int i = 1; i <=21; i=i+4) {
            sum1 = sum1+1.0/i;
        }
        for (int j = 3; j <=19; j=j+4) {
            sum2=sum2+1.0/j;
        }
        sum2 = -sum2;
        double sum = sum1+sum2;
        System.out.println(sum);

    }

}

 

posted @ 2019-04-24 22:37  Geek张东坡  阅读(2436)  评论(0编辑  收藏  举报