Java rounding up to an int using Math.ceil

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

    157/32 is an integer division because all numerical literals are integers unless otherwise specified with a suffix (d for double l for long)

    the division is rounded down (to 4) before it is converted to a double (4.0) which is then rounded up (to 4.0)

    if you use a variables you can avoid that

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

提交回复
热议问题