老师出的题目 pai=4-4/3+4/5-4/7+4/9-4/11....................
请问怎么写呢

解决方案 »

  1.   


    double result = 4;
    for(int i=1;i<10000;i++){
    if(i%2==1){
    result -= (4.0/(i*2+1));
    }else{
    result += (4.0/(i*2+1));
    }
    }
    System.out.println(result);越增加循环次数,得到的值越精确
      

  2.   


    /**
     * JDK 5.0
     */public class PI {
    public static void main(String[] args){
    double result = 1.0;
    int down = 3;
    int count = 1;
    double tmp = 1.0 / 3;
    while( Math.abs( tmp ) > 0.0001 ) {
    result += ( count++%2 == 1 ? -tmp : tmp );
    down += 2;
    tmp = 1.0 / down;
    }
    System.out.println(result*4);
    }
    }