将两个整数相除并将结果四舍五入为最接近的整数
Dividing two integers and rounding up result to nearest integer
我有两个整数 a,b 总是 >= 0。我想将 a 除以 b 并且 return 向上舍入百分比到最接近的整数。
示例:18/38 应该 return 47,13/38 应该 return 34。
我怎样才能做到这一点?
我尝试了以下但没有用
c = Math.round(a/b) * 100;
由于 a
和 b
是整数,a/b
将使用 integer division, and only return the "whole" part of the result. Instead, you should multiply a
by 100.0
(note the .0
, which makes it a double
literal!) to use floating-point division, and then ceil
结果,并将其截断为 int
:
c = (int) Math.ceil(100.0 * a / b);
c = (int) Math.round(100.0 * a / b);
这应该会产生预期的结果。
您需要执行以下操作才能获得结果
Double res= Double.valueof(a/b);
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String num= decimalFormat.format(res);
Int finalResult = Integer.valueof(num)*100;
谢谢
public static void main(String[] args){
int a=18,b=38,c=0;
c = (int) Math.round(100.0 * a / b);
System.out.println(c);
}
正如@Mureinik 所说 a
和 b
是整数,它们将使用整数除法。
你应该用上面的a乘以100。并继续使用 .round
而不是 .ceil
以获得 47 作为预期的输出 .ceil
将为您提供 48 作为输出。
我有两个整数 a,b 总是 >= 0。我想将 a 除以 b 并且 return 向上舍入百分比到最接近的整数。
示例:18/38 应该 return 47,13/38 应该 return 34。
我怎样才能做到这一点?
我尝试了以下但没有用
c = Math.round(a/b) * 100;
由于 a
和 b
是整数,a/b
将使用 integer division, and only return the "whole" part of the result. Instead, you should multiply a
by 100.0
(note the .0
, which makes it a double
literal!) to use floating-point division, and then ceil
结果,并将其截断为 int
:
c = (int) Math.ceil(100.0 * a / b);
c = (int) Math.round(100.0 * a / b);
这应该会产生预期的结果。
您需要执行以下操作才能获得结果
Double res= Double.valueof(a/b);
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String num= decimalFormat.format(res);
Int finalResult = Integer.valueof(num)*100;
谢谢
public static void main(String[] args){
int a=18,b=38,c=0;
c = (int) Math.round(100.0 * a / b);
System.out.println(c);
}
正如@Mureinik 所说 a
和 b
是整数,它们将使用整数除法。
你应该用上面的a乘以100。并继续使用 .round
而不是 .ceil
以获得 47 作为预期的输出 .ceil
将为您提供 48 作为输出。