有一道踢,计算e的x次方,计算公式:e(x)=1+x(1)/1!+x(2)/2!+.....+x(n)/n!
x(n)代表x的n次方,我不知道怎么写好.n!代表n的阶乘
我的程序这样的
import java.awt.*;
import java.applet.*;public class EX extends Applet{
  Label lab1,lab2;
  TextField input1,input2;
  int x,n,temp;
  double result;
  public void init(){
    lab1=new Label("输入x值");
    lab2=new Label("输入n值");
    input1=new TextField(10);
    input2=new TextField(10);
    add(lab1);
    add(input1);
    add(lab2);
    add(input2);
  }  public void paint(Graphics g){
    g.drawString("e在n值为"+n+"情况下的"+x+"方为    "+result,10,60);
  }  public boolean action(Event e,Object o){
    temp=1;
    if(e.target==input1||e.target==input2){
      x=Integer.parseInt(input1.getText());
      n=Integer.parseInt(input2.getText());
      if(x==0){
        result=1;
        repaint();
        return true;
      }else{
        for(int i=1;i<=n;i++){
            for(int j=1;j<=i;j++)
                  temp*=j;
          result+=Math.pow(x,i)/temp;
        }
      }
    }
    repaint(); 
    return true;
  }
}
结果老和自己算的不对,不知道程序错哪里了

解决方案 »

  1.   

    调整了部分语句的顺序:public boolean action(Event e,Object o){
            result=1; ////<----
            if(e.target==input1||e.target==input2){
                x=Integer.parseInt(input1.getText());
                n=Integer.parseInt(input2.getText());
                if(x==0){
                    repaint();
                    return true;
                }else{
                    for(int i=1;i<=n;i++){
                        temp=1; ////<-
                        for(int j=1;j<=i;j++)temp*=j;
                        result+=Math.pow(x,i)/temp;
                    }
                }
            }
            repaint();
            return true;
        }
      

  2.   

    哦,temp是没看清,谢谢
    那为什么result要在那里赋值?后面不一样吗?
      

  3.   

    if(x==0){
          result=1;
           repaint();
           return true;
    }原来是在 x==0 的时候才赋值为1,x不为0时呢?就保留上次计算的值了。
    当n较大时,temp就溢出了,
      

  4.   

    Applet开始执行时的顺序:
    1、init()
    2、start()
    3、paint()---------------------------------可以另外搞一个类变量 String s="";
    g.drawString(s,10,60);计算出e值以后再:
     s = "e在n值为"+n+"情况下的"+x+"方为    "+result;