【java/math】使用Math.ceil函数求总数/批次大小/搬运次数中的搬运次数(一行流代码)

【需求】

已知总数,批次大小,求搬运次数;

已知总记录数,每页规模,求页数;

已知总数据量,线程能承担的数量量,求使用到的线程总数;

【难点】

次数=总数/批次大小的问题,难点在于有无余数,代码容易冗长。

【解决方案】

Math.ceil 函数可以一行代替数行,是一行流代码。

【示例代码】

package com.hy.lab.batchCnt;

public class Test {
    public static void main(String[] args){
        final int batchSize=10;
        int[] arr={100,101,120,123,140,145,149};

        for(int count:arr){
            int times=(int)Math.ceil((double)count/(double)batchSize);
            String msg=String.format("总数=%d,批次大小=%d,得搬运%d次才能搬完",count,batchSize,times);
            System.out.println(msg);
        }
    }
}

【输出】

总数=100,批次大小=10,得搬运10次才能搬完
总数=101,批次大小=10,得搬运11次才能搬完
总数=120,批次大小=10,得搬运12次才能搬完
总数=123,批次大小=10,得搬运13次才能搬完
总数=140,批次大小=10,得搬运14次才能搬完
总数=145,批次大小=10,得搬运15次才能搬完
总数=149,批次大小=10,得搬运15次才能搬完

END

posted @ 2022-07-13 14:35  逆火狂飙  阅读(192)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东