java - 为什么在运行此代码时会得到一个四舍五入的输出?
问题描述
我试图让这段代码将英寸转换为英尺,但是每当我尝试获得输出时,我发现它被四舍五入,即使我将它作为浮点数返回。
我曾尝试更改代码以执行模数函数 + 除法函数,但只给出了余数。我是编码新手,所以这可能真的很容易,只是似乎无法弄清楚。
``````````````````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
解决方案
您将一个整数传递给该方法并除以 an int
,因此结果将始终为 an int
。要解决此问题,只需将您的方法更改为:
public static float calcFeetAndInchesToCentimeters(float inches){}
推荐阅读
- ios - ios - 根据屏幕大小调整按钮的宽度和高度
- windows - 菜鸟问:如何将空文件夹推送到我的 BitBucket git repo
- python - 如何计算 Django 中跨字段的值?
- laravel - 为什么验证消息没有与 required_if 一起出现?
- python - 如何使用 Lmfit 和 Python 解决 NaN 值错误
- javascript - 如何禁用 setInterval 功能并重新启动
- vue.js - 小吃店会在 3 秒后自动关闭。如何在 vue 中关闭小吃店后将状态设置为 false
- python-3.x - 永久存储访问过的链接,以免明天访问
- c++ - 将字符串存储为十六进制而不转换
- windows - 在 Windows 中的 weblogic 平台上,Hive 与 Kerberized Hadoop 集群的连接失败