Java 使用数学类将双精度舍入为整数

Java 使用数学类将双精度舍入为整数,java,math,rounding,Java,Math,Rounding,我一直在尝试使用舍入方法将unitTotal(double)变成一个整数,然后将整数赋给mark变量。我一直被这个问题困扰着,我不知道我做错了什么。如果有人能向我解释我做错了什么,我将不胜感激。多谢各位 public class GradeCalculator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double unitTotal; int m

我一直在尝试使用舍入方法将
unitTotal
(double)变成一个整数,然后将整数赋给mark变量。我一直被这个问题困扰着,我不知道我做错了什么。如果有人能向我解释我做错了什么,我将不胜感激。多谢各位

public class GradeCalculator {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    double unitTotal;
    int mark;
    String grade; 

    System.out.println("Enter your unit total score");
    unitTotal = sc.nextDouble();
    Math.round(unitTotal); 

    mark = unitTotal;

应将舍入结果指定给变量:

mark = (int) Math.round(unitTotal);

请注意,
Math
课程建议将
double
四舍五入为
long
。通过强制转换到
int
您可能会失去精度。

您可以使用
sc.nextFloat()取而代之。然后,您可以使用返回的
int
并将其分配给
mark

mark = Math.round(sc.nextFloat()); 

如果你想要的是一种将一个双精度整数四舍五入到最接近的整数的方法,那么我有一个想法,尽管它没有使用库方法

public int round(double value) {
    int cutDecimals = (int) value;  // This cuts the decimals entirely, rounding down
    double decimals = value - ((double) cutDecimals);  // Gives only the decimals
    if(decimals < 0.5) return cutDecimals;  // If the decimals is less than 0.5 we return the rounded down number
    else return cutDecimals + 1;  // If the decimals is over 0.5 we round up
}
公共整数舍入(双值){
int cutDecimals=(int)value;//这会将小数全部舍入
double decimals=值-((double)cutDecimals);//只给出小数
如果(小数<0.5)返回cutDecimals;//如果小数小于0.5,则返回向下舍入的数字
else返回cutDecimals+1;//如果小数超过0.5,我们将进行四舍五入
}
根据,
Math.round
方法在传递值为
double
时返回
long
,在传递值为
float
时返回
int

标记的类型更改为
long
,或者需要手动将
long
转换为
int
。请记住,如果返回值大于
Integer.MAX\u value
,则可能引发异常

此外,还需要将返回值存储到变量中

 Math.round(unitTotal); 
取代

 mark = Math.round(unitTotal); 

HTH.

您共享的代码是否完整?我终于明白了,现在它非常有意义。非常感谢。