[英]how to get double to round up to nearest integer?
提示说“编写一个程序,将两个双精度数作为输入,然后在它们都四舍五入到最接近的整数时打印数字的总和。您可以假设双精度输入始终为正数。”
我写的是:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble();
double hit_2 = scan.nextDouble();
double hit_add = (hit_1 + hit_2 + 0.5);
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + (int)hit_add);
对于大多数小数,它四舍五入,但我想要的是像 4.5 这样的数字四舍五入到 5。现在,它四舍五入 4.5 到 4。我加了 0.5 试图让双精度数四舍五入,但它没有工作。 我也不允许使用 Math.round() 或类似的东西。
像这样创建自己的圆形方法。 转换为int,然后找到余数。 如果余数 >= 0.5,只需将 integer 加 1。 见下文:
private static int round(double d){
int i = (int)d;
double remainder = d - i;
if(remainder>=0.5){
i++;
}
return i;
}
然后你可以在你的双人上使用那个方法
只需要+0.5:
double a = 1.8, b = 1.2;
System.out.println((int)(a + 0.5));
System.out.println((int)(b + 0.5));
System.out.println((int)(a + 0.5) + (int)(b + 0.5));
对于您的代码:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble() + 0.5;
double hit_2 = scan.nextDouble() + 0.5;
int hit_1P2 = (int)hit_1 + (int)hit_2;
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + hit_1P2);
有两种方法可以将双精度舍入到最接近的 integer。
一个。 使用类型转换为 int 示例:如果 double 将值保持为 3.26,则小数点后的所有数字都将丢失。
湾。 使用 Math.round() function - 这会将 0.5 添加到两倍并四舍五入到最接近的 integer。
示例:如果 double 保持值为 3.7,则此 function 将添加 0.5 并四舍五入为最接近的 integer。 类似地,如果 double 值是 3.2,那么 Math.round() 将添加 0.5,所以这将变为 3.7,在这种情况下最接近的 integer 仍然是 3
以下是上述两个示例的示例代码块
double d = 3.5;
int typeCastInt = (int) d;
int t = (int) Math.round(d);
System.out.println(typeCastInt); //prints 3
System.out.println(t); //Prints 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.