private static final double is 0

我与影子孤独终老i 提交于 2019-12-12 14:47:09

问题


I am trying to use the following line to specify a double constant, can anybody help explain to me why at runtime this constant has a value of 0.0:

private static final double CONSTANT = 1/2;

回答1:


1 and 2 are interpreted as integers and produce integer result of division. Add D at the end to make them interpreted as doubles.

private static final double CONSTANT = 1D/2D;



回答2:


The constant ends up with a value of 0.0 because the result of integer division is an integer, truncated. So your the value of your initialization is 0, not 0.5. To force a double result, make one or both of the operands a double:

private static final double CONSTANT = 1/2.0;  // or 1/2D, or even 1D/2D 


来源:https://stackoverflow.com/questions/11812912/private-static-final-double-is-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!