整数除法:为什么1/3 == 0的结果? [英] Int division: Why is the result of 1/3 == 0?

查看:246
本文介绍了整数除法:为什么1/3 == 0的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写以下代码:

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,或者甚至只是 first ,然后使用浮点运算,得到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的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆