java 为什么 1 / 2 == 0 使用 double ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36902784/
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
Why does 1 / 2 == 0 using double?
提问by Benton Justice
I'm a high school student currently getting ready for a state academic meet(UIL). I have a problem and I've looked everywhere and can't seem to find an answer! Why does this print out 0.0?
我是一名高中生,目前正在准备参加州学术会议 (UIL)。我有一个问题,我到处找,似乎找不到答案!为什么这会打印出 0.0?
double d = 1/2;
System.out.println(d);
回答by Suresh Atta
It's because of the data type.
这是因为数据类型。
When you do 1/2
that is integer division because two operands are integers, hence it resolves to zero (0.5 rounded down to zero).
当你这样做时1/2
是整数除法,因为两个操作数是整数,因此它解析为零(0.5 向下舍入为零)。
If you convert any one of them to double, you'll get a double result.
如果您将其中任何一个转换为双精度,您将得到双精度结果。
double d = 1d/2;
or
或者
double d = 1/2.0;
回答by shmosel
1 and 2 are both integers, so 1 / 2 == 0
. The result doesn't get converted to double
until it's assigned to the variable, but by then it's too late. If you want to do float division, do 1.0 / 2
.
1 和 2 都是整数,所以1 / 2 == 0
。在将结果double
分配给变量之前,不会将结果转换为,但为时已晚。如果要进行浮动除法,请执行1.0 / 2
.
回答by Bohemian
It's because 1
and 2
are int
values, so as per the java language spec, the result of an arithmetic operation on int
operands is also int
. Any non-whole number part of the result is discarded - ie the decimal part is truncated, 0.5
-> 0
这是因为1
和2
是int
值,所以根据 java 语言规范,对int
操作数进行算术运算的结果也是int
. 结果的任何非整数部分都被丢弃——即小数部分被截断,0.5
->0
There is an automatic widening cast from int
to double
when the value is assigned to d
, but cast is done on the int
result, which is a whole number 0
.
当将值分配给 时,会自动从int
to扩大强制double
转换d
,但对int
结果进行强制转换,结果是一个整数0
。
If "fix" the problem, make one of the operands double
by adding a "d" to the numeric literal:
如果“修复”问题,请double
通过向数字文字添加“d”来创建操作数之一:
double d = 1d/2;
System.out.println(d); // "0.5"
As per the language spec, when one of the operands of an arithmetic operation is double
, the result is also double
.
根据语言规范,当算术运算的操作数之一是 时double
,结果也是double
。
回答by Krulig
Cause result of 1/2 = 0 and then result is parsing to double. You're using int instead of double. I think it should be ok:
导致 1/2 = 0 的结果,然后结果解析为双倍。您使用的是 int 而不是 double。我觉得应该没问题:
double d = 1/2.0;
System.out.println(d);
Sorry for weak english
抱歉英语不好