Double value returns 0 [duplicate]

末鹿安然 提交于 2019-11-26 05:39:07

问题


Here\'s an example:

Double d = (1/3);
System.out.println(d);

This returns 0, not 0.33333... as it should.

Does anyone know?


回答1:


That's because 1 and 3 are treated as integers when you don't specify otherwise, so 1/3 evaluates to the integer 0 which is then cast to the double 0. To fix it, try (1.0/3), or maybe 1D/3 to explicitly state that you're dealing with double values.




回答2:


If you have ints that you want to divide using floating-point division, you'll have to cast the int to a double:

double d = (double)intValue1 / (double)intValue2

(Actually, only casting intValue2 should be enough to have the intValue1 be casted to double automatically, I believe.)




回答3:


Use double and not Double unless you need to use these values in the object sense. Be aware about the Autoboxing concepts



来源:https://stackoverflow.com/questions/366237/double-value-returns-0

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