为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我在运行这段代码时会得到一个四舍五入的输出?

为什么我在运行这段代码时会得到一个四舍五入的输出?

PIPIONE 2022-11-30 10:53:55
我试图让这段代码将英寸转换为英尺,但每当我尝试获取输出时,我发现它被四舍五入,即使我将它作为浮点数返回。我曾尝试更改代码以执行模数函数 + 除法函数,但只给出了余数。我是代码新手,所以这可能真的很简单,只是似乎无法弄清楚。`````````````````JAVA```````````````````````````` `` //这是我用来输出的方法。public static void main(String[] args) {    System.out.println(calcFeetAndInchesToCentimeters(34));}//这是我实际用来计算的方法。public static float calcFeetAndInchesToCentimeters(int inches){    if(inches >= 0){        return inches / 12;    }else{        return -1;    } }输出:2.0I would like to have the output be when I run the code above 2.83, however, I am only getting the rounded down version. I am not trying to find a 
查看完整描述

2 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

我试图让这段代码将英寸转换为英尺,但每当我尝试获取输出时,我发现它被四舍五入,即使我将它作为浮点数返回。


我曾尝试更改代码以执行模数函数 + 除法函数,但只给出了余数。我是代码新手,所以这可能真的很简单,只是似乎无法弄清楚。


`````````````````JAVA```````````````````````````` `` //这是我用来输出的方法。


public static void main(String[] args) {

    System.out.println(calcFeetAndInchesToCentimeters(34));

}

//这是我实际用来计算的方法。


public static float calcFeetAndInchesToCentimeters(int inches){

    if(inches >= 0){

        return inches / 12;

    }else{

        return -1;

    }

 }

输出:2.0




I would like to have the output be when I run the code above 2.83, however, I am only getting the rounded down version. I am not trying to find a 


查看完整回答
反对 回复 2022-11-30
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

类型转换英寸以浮动然后划分。


public static float calcFeetAndInchesToCentimeters(int inches) {

    if (inches >= 0) {

        return ((float) inches) / 12;

    } else {

        return -1;

    }

}


查看完整回答
反对 回复 2022-11-30
  • 2 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信