问题描述
我写的是这段代码:
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
结果是0.为什么会这样,我该如何解决这个问题?
The result is 0. Why is this, and how do I solve this problem?
推荐答案
两个操作数(1和3)是整数,因此使用整数运算(此处除法)。将结果变量声明为double只会导致隐式转换在除法后发生 。
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.
整数除法当然会返回除法的真实结果零。因此, 0.333 ...
的结果将向下舍入为0。 (请注意,处理器实际上并没有进行任何舍入,但你可以这样想。)
Integer division of course returns the true result of division rounded towards zero. The result of 0.333...
is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)
另外,请注意,如果两者操作数(数字)以浮点数给出; 3.0和1.0,或者甚至只是第一个,然后使用浮点运算,给你 0.333 ...
。
Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333...
.
这篇关于为什么1/3 == 0的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!