Java 中使用 double 类型进行除法时出错
好的。我已经用头撞墙了大约两个小时,现在试图弄清楚为什么 double answer = 364/365;
告诉我 answer
是 0或任何其他 double 组合,它只是截断小数,我只是不知道为什么。
Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365;
is telling me that answer
is 0. Or any other combination of double
for that matter, its just truncating the decimal and I just don't know why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
364/365 执行整数除法(截断小数)。
尝试使用 double answer = 364.0/365; 强制其执行浮点除法。
类似:
也可以工作,因为其中一个操作数不是整数。
364/365 performs integer division (truncates the decimal).
Try
double answer = 364.0/365;
to force it to perform floating point division.Something like:
would work as well, since one of the operands isn't an integer.
您采用 int 类型 (364) 并除以另一个 int 类型 (365) - 答案将是 int。然后将其存储在双精度类型答案中。您可以执行以下操作:
更多信息请参见:
http://mindprod.com/jgloss/division.html
You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:
More info here:
http://mindprod.com/jgloss/division.html
你需要做双除法。现在,Java 将其解释为整数除法并返回截断的
int
。您需要的是:
或
You need do do double division. Right now Java is interpreting it as integer division and returning the truncated
int
.What you need is:
or
原因是java中整数文字的默认类型是int,并且所有基于int的算术的所有结果都被类型转换回int 。因此,虽然你的答案是 0.997,但当它被类型转换回来时,它变成 0:
所以你可以这样做:
或者
The reason is that the default type of integer literals in java is
int
and all the result of allint
based arithemetic is type casted back toint
. Hence though your answer is 0.997, when it is typecasted back it becomes 0:So you can do like this:
or
以上所有答案都是正确的,我想补充一点,这都是关于 GIGO 的。
在上面的代码中,double类型仅意味着回答变量和算术表达式都有两个int类型的操作数。因此算术表达式的输出也是 int 类型,然后通过自动向上转换为 double 类型给出输出 0.0,就像下面的示例一样:
上面的代码将给出输出 Infinity,因为操作数之一是浮点数,因此通过自动类型转换 0 转换为 0.0,结果与浮点数据类型一致。
而
在运行时会给出 java.lang.ArithmeticException: / by Zero 异常,因为两个操作数都是 int 数据类型,因此无论 ans 变量数据类型是否为 double,输出都是 Integer 数据类型。
All the above answers are right, would just like to add that it is all about GIGO.
in above code double type implies only to answer variable and arithmetic expression has both operands of int type. So the output of the arithmetic expression is also int type which is then through auto up-casting to double type gives output 0.0, just like below examples:
the above code will give output Infinity as one of the operand is Floating-point number so through auto type-casting 0 is converted to 0.0 and the result is as per the Floating-point datatype.
whereas
will give java.lang.ArithmeticException: / by zero exception at runtime since both the operands are of datatype int and so the output is as per the Integer datatype irrespective of ans variable datatype being double.