Java使用double或float计算错误

时间:2015-02-03 15:10:11

标签: java double decimal

我正在尝试使用以下代码为MVC模式的Model部分创建一个Web应用程序:

    public OddsCalcBrain(String _odds, String _personalodds, String _bankroll){

    odds = Double.parseDouble(_odds);
    personalodds = Double.parseDouble(_personalodds) / 100.0d;
    personaloddslose = 1.0d-personalodds;
    bankroll = Double.parseDouble(_bankroll);

    result = bankroll * ((odds * personalodds - personaloddslose) / (2.0d * odds));
}

public String getResult(){
    return Double.toString(result);
}

我在servlet中使用RequestDispatcher将结果转发到JSP页面,它看起来像这样:

     public void doGet(HttpServletRequest request,
         HttpServletResponse response)
 throws ServletException, IOException
 {
     String _personalodds = request.getParameter("personalodds");
     String _odds = request.getParameter("odds");
     String _bankroll = request.getParameter("bankroll");
     OddsCalcBrain brain = new OddsCalcBrain(_personalodds, _odds, _bankroll);

    request.setAttribute("result", brain.getResult());
    RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/oddscalc.jsp");
    dispatcher.forward(request, response);

 }

要打印它,我使用它:

Result: ${result}

结果非常错误。例如,如果:

odds = 3;
personalodds = 0.5; //(The user would enter a percentage, so 50 would be 0.5)
personaloddslose = 0.5;
bankroll = 120;

该公式应该产生20.0,如果我手动将它放在计算器中,它会这样做,但无论我使用float还是double我的变量,它都会给我0.636的结果。为什么会这样,我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

您正在致电:

OddsCalcBrain brain = new OddsCalcBrain(_personalodds, _odds, _bankroll); 
//OddsCalcBrain("50", "3", "120");

而不是

OddsCalcBrain brain = new OddsCalcBrain(_odds, _personalodds, _bankroll);
//OddsCalcBrain("3", "50", "120");