我现在正在尝试这个:
int a = round(n);
我使用了double
类型的变量n
,但代码并没有按照我的期望工作。请问我错在哪里?
我现在正在尝试这个:
int a = round(n);
我使用了double
类型的变量n
,但代码并没有按照我的期望工作。请问我错在哪里?
在这个片段中,round()
方法的返回类型是什么?
如果这是Math.round()
方法,则当输入参数为Double时,它返回一个Long。
因此,你需要将返回值进行强制转换:
int a = (int) Math.round(doubleVar);
如果你不喜欢Math.round(),你也可以使用这个简单的方法:
int a = (int) (doubleVar + 0.5);
Math.round()
显然没有任何有价值的理由:https://dev59.com/OWw15IYBdhLWcg3wqNkB#6468757 - Gauthier BoaglioMath.round()
的人,因为它与你提供的解决方案“字面上”是一样的。就这些了,谢谢。 - Gauthier Boaglio0.5
吗? - Sasha将 double 四舍五入到“最近”的 整数,就像这样:
1.4 -> 1
1.6 -> 2
-2.1 -> -2
-1.3 -> -1
-1.5 -> -2
private int round(double d){
double dAbs = Math.abs(d);
int i = (int) dAbs;
double result = dAbs - (double) i;
if(result<0.5){
return d<0 ? -i : i;
}else{
return d<0 ? -(i+1) : i+1;
}
}
您可以根据自己的需要更改条件(result<0.5)。
Math.round函数是一个重载函数,当它接收到一个浮点值时,会返回一个整数值。例如:
int a=Math.round(1.7f);
当它接收到一个双精度浮点数时,它会给你一个长整型,因此你需要将其强制转换为整型。
int a=(int)Math.round(1.7);
这是为了防止精度丢失。你的double值是64位,但int变量只能存储32位,因此它会将其转换为long,长整型是64位,但可以按照上述方式强制转换为32位。
import java.math.*;
public class TestRound11 {
public static void main(String args[]){
double d = 3.1537;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
}
public static double round(double d, int decimalPlace){
// see the Javadoc about why we use a String in the constructor
// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
}
public static int round(double d) {
if (d > 0) {
return (int) (d + 0.5);
} else {
return (int) (d - 0.5);
}
}
Math.round
的文档说明:
返回将参数四舍五入到整数的结果。结果相当于
(int) Math.floor(f+0.5)
。
不需要强制转换为 int
。也许这是从过去改变的。
round()
方法。你需要调用Math.round(n)
,或者静态导入Math.round
,然后像你所做的那样调用它。