运行 这段代码时,为什么我得到一个四舍五入的输出?
Why am I getting a rounded output when running this code?
我试图让此代码将英寸转换为英尺,但每当我尝试获取输出时,我发现它被四舍五入,即使我将它作为浮点数返回也是如此。
我试过更改代码来执行取模函数+除法函数,但只给出了余数。我是代码新手,所以这可能真的很简单,只是似乎无法弄清楚。
`````````````````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
您将一个整数传递给该方法并除以 int
,因此结果将始终为 int
。要解决此问题,只需将您的方法更改为:
public static float calcFeetAndInchesToCentimeters(float inches){}
强制转换英寸以浮动然后除法。
public static float calcFeetAndInchesToCentimeters(int inches) {
if (inches >= 0) {
return ((float) inches) / 12;
} else {
return -1;
}
}
您可以将整数转换为浮点数,然后尝试
public static float calcFeetAndInchesToCentimeters(int inches){
if(inches >= 0){
return (float)inches / 12;
}else{
return -1;
}
}
我试图让此代码将英寸转换为英尺,但每当我尝试获取输出时,我发现它被四舍五入,即使我将它作为浮点数返回也是如此。
我试过更改代码来执行取模函数+除法函数,但只给出了余数。我是代码新手,所以这可能真的很简单,只是似乎无法弄清楚。
`````````````````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
您将一个整数传递给该方法并除以 int
,因此结果将始终为 int
。要解决此问题,只需将您的方法更改为:
public static float calcFeetAndInchesToCentimeters(float inches){}
强制转换英寸以浮动然后除法。
public static float calcFeetAndInchesToCentimeters(int inches) {
if (inches >= 0) {
return ((float) inches) / 12;
} else {
return -1;
}
}
您可以将整数转换为浮点数,然后尝试
public static float calcFeetAndInchesToCentimeters(int inches){
if(inches >= 0){
return (float)inches / 12;
}else{
return -1;
}
}