java 双精度值返回 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/366237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:06:47  来源:igfitidea点击:

Double value returns 0

javadivision

提问by oletk

Here's an example:

下面是一个例子:

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

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

这将返回 0,而不是 0.33333... 应该如此。

Does anyone know?

有人知道吗?

回答by Firas Assaad

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

那是因为1and3被视为integers当您没有另外指定时,因此1/3计算为integer0,然后将其强制转换为double0. 要修复它,请尝试(1.0/3),或者1D/3明确说明您正在处理双重值。

回答by coobird

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

如果您int想使用浮点除法来除 s ,则必须将s 强制转换int为 a double

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

(Actually, only casting intValue2should be enough to have the intValue1be casted to doubleautomatically, I believe.)

(事实上,只有铸造intValue2应该是足够有intValue1被强制转换为double自动,我相信。)

回答by Vijay Dev

Use doubleand not Doubleunless you need to use these values in the object sense. Be aware about the Autoboxingconcepts

除非您需要在对象意义上使用这些值,否则请使用double而不是Double。注意自动装箱概念