Java rounding up to an int using Math.ceil

前端 未结 15 1704
陌清茗
陌清茗 2020-11-29 17:42
int total = (int) Math.ceil(157/32);

Why does it still return 4? 157/32 = 4.90625, I need to round up, I\'ve looked around and this se

15条回答
  •  囚心锁ツ
    2020-11-29 18:24

    Java provides only floor division / by default. But we can write ceiling in terms of floor. Let's see:

    Any integer y can be written with the form y == q*k+r. According to the definition of floor division (here floor) which rounds off r,

    floor(q*k+r, k) == q  , where 0 ≤ r ≤ k-1
    

    and of ceiling division (here ceil) which rounds up r₁,

    ceil(q*k+r₁, k) == q+1  , where 1 ≤ r₁ ≤ k
    

    where we can substitute r+1 for r₁:

    ceil(q*k+r+1, k) == q+1  , where 0 ≤ r ≤ k-1
    


    Then we substitute the first equation into the third for q getting

    ceil(q*k+r+1, k) == floor(q*k+r, k) + 1  , where 0 ≤ r ≤ k-1
    

    Finally, given any integer y where y = q*k+r+1 for some q,k,r, we have

    ceil(y, k) == floor(y-1, k) + 1
    

    And we are done. Hope this helps.

提交回复
热议问题