【问题标题】:Rounding up a number to 5 or 10 in Java [duplicate]在 Java 中将数字四舍五入为 5 或 10 [重复]
【发布时间】:2026-02-22 06:25:01
【问题描述】:

谁能帮我弄清楚如何在Java中编写一个将数字四舍五入到最接近的5或10的代码。 例如 : 4变成5 1变成5 8变成10 48变成50 43变成45

【问题讨论】:

    标签: java numbers rounding


    【解决方案1】:

    你可以试试这个……

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t;
        while(sc.hasNext()) {
            t = sc.nextInt();
            int x = t % 5 == 0 ? 0 : 1;
            System.out.println(((t/5) + x) * 5);
        }
    }
    

    【讨论】:

    • 您也可以更一般地使用(t + 4) / 5 * 5(t + n - 1) / n * n
    【解决方案2】:

    逻辑很简单,根据余数计算余数和递增值。

    int x=11;
    if(x%10>5) {
        x=x+(10-x%10);
    }else if(x%10>0) {
        x=x+(5-x%5);
    }
    System.out.println(x);
    

    【讨论】: