Java實驗(2) Pi的近似值

使用下式計算PI的近似值並顯示。其中i的值由用戶輸入。

要求使用JOptionPane.showInputDialog作爲輸入,JOptionPane.showMessageDialog作爲輸出。


                                                


設計:

                                                                     


import javax.swing.*;
public class Pi {
    public static void main(String[] args) {
        String input =  JOptionPane.showInputDialog("Enter an input as i");
        int i = Integer.parseInt(input); //注意從對話框輸入的值是字符串型,要先轉換爲整型再進行運算
        double pi,temp = 0;
        for(int j = 1;j <= i;j++){
            temp += Math.pow(-1,j+1) / (2*j-1);
        }
        pi = 4 * temp;
        JOptionPane.showMessageDialog(null, "Pi約等於: "+pi);
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章