Java rounding up to an int using Math.ceil

前端 未结 15 1664
陌清茗
陌清茗 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:18

    In Java adding a .0 will make it a double...

    int total = (int) Math.ceil(157.0 / 32.0);
    
    0 讨论(0)
  • 2020-11-29 18:20
    int total = (157-1)/32 + 1
    

    or more general

    (a-1)/b +1 
    
    0 讨论(0)
  • 2020-11-29 18:22

    Also to convert a number from integer to real number you can add a dot:

    int total = (int) Math.ceil(157/32.);
    

    And the result of (157/32.) will be real too. ;)

    0 讨论(0)
  • 2020-11-29 18:22
    int total = (int) Math.ceil( (double)157/ (double) 32);
    
    0 讨论(0)
  • 2020-11-29 18:24

    Nobody has mentioned the most intuitive:

    int x = (int) Math.round(Math.ceil((double) 157 / 32));
    

    This solution fixes the double division imprecision.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题