gpt4 book ai didi

Java 使用 double 或 float 时计算错误

转载 作者:行者123 更新时间:2023-12-01 11:57:44 25 4
gpt4 key购买 nike

我正在尝试使用以下代码为 MVC 模式的模型部分创建一个 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。为什么会这样,我该如何正确地做到这一点?

最佳答案

您正在调用:

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

而不是

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

关于Java 使用 double 或 float 时计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com