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.您共享的代码是否完整?我终于明白了,现在它非常有意义。非常感谢。