用leibiniz序列计算pi到第n项

时间:2014-09-29 01:11:56

标签: java eclipse

嘿我必须创建一个方法,我必须使用leibiniz序列计算pi到一个通过的术语(a)。这就是我到目前为止所拥有的

public static double calculatePi(int a){
    double oddNum=1;
    double pi=0;
    for(int x=0; x<a; x++){
        if(x%2==0)
            pi=pi+(4/oddNum);
        else
                pi=pi-(4/oddNum);
        oddNum=oddNum+2;
    }
return pi;
}

我还需要帮助编写一个接受传递字符串和(x)术语的方法。在该方法中,它将添加一个&#34;#&#34;每x个字母。因此,如果它通过(圣代,2)它将返回su#nd#ae#。我把它的大部分都放下了但是这是一个逻辑错误,它不允许像(猫,3)那样编译。

public static String addPounds(String s, int x){
    String a="";
    for(int i=0; i<s.length(); i=i+x){
        a=(a+s.substring(i,i+x)+"#");
    }
    return a;
}

非常感谢!

2 个答案:

答案 0 :(得分:0)

你的addPounds方法抛出一个给定示例的StringIndexOutOfBoundsException(cats,3)。

for(int i=0; i<s.length(); i=i+x){
    a=(a+s.substring(i,i+x)+"#");
}

在第一次执行此for循环时,您的变量&#39; a&#39;将正确地成为&#34; Cat#&#34;。但现在它出了问题。 变量&#39; i&#39;增加到3.现在你想得到一个从索引3开始并以索引6结束的子字符串。字符串&#34; Cats&#34;只有4个字母,因此IndexOutOfBoundsException。

我想解决问题的最简单方法是插入if else语句:

for(int i=0; i<s.length(); i=i+x){
        if(s.length()>=i+x){
            a=(a+s.substring(i,i+x)+"#");
        }
        else{
            a= a+s.substring(i);
        }
    }

答案 1 :(得分:0)

你的pi方法运行正常。

您应该将另一个更改为此。我写的有点不同,所以你很容易得到逻辑。

public static String addPounds(String s, int x){
    String a = "";

    //starting from 1 so i can do mod division easily
    for(int i = 1; i <= s.length(); i++){

        //check if next # has to be placed at the end
        if(i + 1 > s.length() && (i + 1) % x == 0){
            a += "#";

        //check if next # has to be placed somewhere inside the string
        }else if(i % x == 0){
            a += s.charAt(i - 1);
            a += "#";

        //oherwise just add the char at i-1
        }else {
            a += s.charAt(i - 1 );

        }
    }
    return a;
}