//求出e=1+1/1!+1/2!+1/3!+……+1/n!+……的近似值,要求误差小于0.0001import java.applet.*;import java.awt.*;import java.awt.event.*;public class at1_1 extends applet implements actionlistener{ textfield text1; button button1; public void init() { text1 = new textfield("0",10); button1 = new button("清除"); add(text1); add(button1); text1.addactionlistener(this); button1.addactionlistener(this); } public void start(){} public void stop(){} public void destory(){} public void paint(graphics g) { g.drawstring("在文本区输入数字n后回车",10,100); g.drawstring("文本区显示1+1/1!+1/2!+1/3!+……+1/n!+……的近似值",10,120); } public void actionperformed(actionevent e) { if(e.getsource()==text1) { double sum=1,a=1; int i=1; int n=0; try { n = integer.valueof(text1.gettext()).intvalue(); while(i<=n) { a = a*(1.0/i); sum = sum + a; i=i+1; } sum=sum*10000; sum=math.round(sum); sum=sum/10000; text1.settext(""+sum); } catch(numberformatexception event) { text1.settext("请输入数字字符"); } } else if(e.getsource()==button1) { text1.settext("0"); } }}
闽公网安备 35060202000074号