使用下式計算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);
}
}