Three methods of rounding up

Method one: Check the remainder

Still cultivate the habit of it this way, because he usually can not go wrong

if (temp%k == 0)
    result = temp / k ;
else
    result = (temp / k)+1;

Method Two: Add a little processing (recommended, but may overflow)

result = (temp +k-1)/ k;

This can give yourself an example to try to understand

Method three: Use cmath header file ceil function (not recommended, may be wrong)

result = (int)ceil(temp / k);

The biggest problem: Math.ceil return type is double

Accuracy loss may only occur under very extreme scenario, but once there is an implicit bug is very difficult to troubleshoot.

for example:

  1. Ceil two numbers assume a calculation originally 2.0, but due to accuracy problems, in fact, the result is 1.9999999999999999999999999 ceil

  2. When converted to an int result, the loss of precision occurs, the calculation result is converted to a 2.0 1

In any possible compared with floating-point data, or floating-point and integer type conversion must pay close attention.

Reference link: https: //www.jianshu.com/p/29ce2fb998b4

Guess you like

Origin www.cnblogs.com/zlszls3113373723/p/11918001.html