Java Math.ceil() has pits in rounding up

Math.ceil(.95);    // 1
Math.ceil(4);      // 4
Math.ceil(7.004);  // 8
Math.ceil(-0.95);  // -0
Math.ceil(-4);     // -4
Math.ceil(-7.004); // -7
It can be seen that Math.ceil() rounds up an integer of type int and is always the current value

Therefore, when we calculate int integers in Math.ceil, we should use a double type number

error:

int a,b
int c= (int) Math.ceil( a / b);	 //没有意义 Math.ceil计算的值永远等于a / b的值

correct:

int a,b
int c= (int) Math.ceil( a * 1.0 / b);	//int整数运算向上转型变成double双精度运算 Math.ceil有意义

Guess you like

Origin blog.csdn.net/qq_41490274/article/details/100171419