将两个整数相除并将结果四舍五入到最接近的整数

时间:2019-05-07 17:38:13

标签: java percentage division

我有两个整数a,b始终> =0。我想将a除以b,然后将四舍五入的百分比返回到最接近的整数。

例如:18/38应该返回47,而13/38应该返回34。

我该怎么做?

我尝试了以下操作,但没有成功

c = Math.round(a/b) * 100;

4 个答案:

答案 0 :(得分:2)

由于ab是整数,因此a/b将使用integer division,并且仅返回结果的“整个”部分。相反,您应该将a乘以100.0(请注意.0,这使其成为double文字!)才能使用浮点除法,然后再使用{{3} }结果,并将其截断为int

c = (int) Math.ceil(100.0 * a / b);

答案 1 :(得分:0)

c = (int) Math.round(100.0 * a / b);

这应该可以得到预期的结果。

答案 2 :(得分:0)

您需要遵循以下步骤来获得结果

Double res= Double.valueof(a/b);
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String num= decimalFormat.format(res);
Int finalResult = Integer.valueof(num)*100;

谢谢

答案 3 :(得分:0)

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所说的ab是整数,它们将使用整数除法。 您应将100乘以上面的数字。并继续使用.round而不是.ceil以获得47作为输出,而.ceil将会给您48作为输出。