java程序使用int和double [英] java program using int and double

查看:243
本文介绍了java程序使用int和double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的Java程序,如下所示:

I have written a simple Java program as shown here:

public class Test {

    public static void main(String[] args) {
        int i1 =2;
        int i2=5;
        double d = 3 + i1/i2 +2;
        System.out.println(d);
    }
}

因为变量 d 被声明为double我期待这个程序的结果是 5.4 但我得到的输出为 5.0

Since variable d is declared as double I am expecting the result of this program is 5.4 but I got the output as 5.0

请帮助我理解这一点。

推荐答案

i1 / i2 将为0.由于 i1 i2 是两个整数。

i1/i2 will be 0. Since i1 and i2 are both integers.

如果你有 int1 / int2 ,如果答案不是一个完整的整数,小数点后面的数字将被删除。在你的情况下, 2/5 是0.4,所以你会得到0。

If you have int1/int2, if the answer is not a perfect integer, the digits after the decimal point will be removed. In your case, 2/5 is 0.4, so you'll get 0.

你可以施放 i1 i2 double (另一个将被隐式转换)

You can cast i1 or i2 to double (the other will be implicitly converted)

double d = 3 +(double)i1 / i2 +2;

这篇关于java程序使用int和double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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