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

查看:32
本文介绍了int 除法:为什么结果是 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,甚至只是第一个,然后使用浮点运算,得到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....

这篇关于int 除法:为什么结果是 1/3 == 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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