e = 1 + 1/1! + 1/2! + 1/3! + ... + 1/n!。當 1/(n+1)! < 0.0001 時截斷,滿足精度要求。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EApproximationApplet extends Applet implements ActionListener {
TextField input;
Button clearBtn;
public void init() {
input = new TextField("0", 10);
clearBtn = new Button("清除");
add(input); add(clearBtn);
input.addActionListener(this);
clearBtn.addActionListener(this);
}
public void paint(Graphics g) {
g.drawString("在文本框輸入 n 後回車", 10, 100);
g.drawString("顯示 1 + 1/1! + ... + 1/n! 近似值", 10, 120);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == input) {
try {
int n = Integer.parseInt(input.getText());
double sum = 1.0, term = 1.0;
for (int i = 1; i <= n; i++) {
term /= i; // 遞推計算 1/i!
sum += term;
}
// 四捨五入到小數點後 4 位
sum = Math.round(sum * 10000) / 10000.0;
input.setText(String.valueOf(sum));
} catch (NumberFormatException ex) {
input.setText("請輸入整數");
}
} else if (e.getSource() == clearBtn) {
input.setText("0");
}
}
}
term /= i 避免重複階乘,效率 O(n)。Math.round(x * 10000) / 10000.0 實現四捨五入保留 4 位小數。編譯後配合 HTML <applet code="EApproximationApplet.class" width=300 height=200></applet> 在瀏覽器或 appletviewer 中運行。