You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中正确使用Mod运算符实现草坪面积与修剪时间向上取整问题求助

修复Mod运算符实现向上取整与时间格式化的问题

问题核心

你当前代码的主要问题:

  • 修剪时间的向上取整逻辑错误,%运算符无法实现向上取整,需结合专用方法
  • 注释的嵌套if语句位置错误,且浮点数直接用==判断相等会因精度问题失效
  • 草坪面积的向上取整需求未落实,原代码仅保留两位小数而非向上取整

修改后的代码(完全保留原风格)

package Tutorial;

import java.util.Scanner;

public class Tut3 {

    public static void main(String[] args) {
        double lgh = 0.0, wdt = 0.0, area = 0.0, mo = 5, mo_time = 0.0;
        Scanner key = new Scanner(System.in);
        System.out.print("\nPlease enter lenght in meters\t");
        lgh = key.nextDouble();
        System.out.print("\nPlease enter width in meters\t");
        wdt = key.nextDouble();
        
        // 对草坪面积向上取整(若需保留两位小数,改为Math.ceil(lgh*wdt*100)/100)
        area = Math.ceil(lgh * wdt);
        mo_time = area / mo;
        // 对修剪时间向上取整,确保不足1分钟按1分钟计算
        mo_time = Math.ceil(mo_time);
        
        // 用精度阈值判断是否为整小时,避免浮点数精度误差
        boolean isWholeHour = Math.abs(mo_time % 60) < 0.0001;
        
        if (mo_time < 60) {
            System.out.printf("\nLawn area = %.0f m2\n\nMowing time %.0f mins ", area, mo_time);
        } else if (mo_time >= 60 && mo_time <= 90) {
            if (isWholeHour) {
                System.out.printf("\n***Lawn area = %.0f m2\n\nMowing time %.0f hour", area, mo_time / 60);
            } else {
                System.out.printf("\n***Lawn area = %.0f m2\n\nMowing time %.1f hour %.0f mins ", area, mo_time / 60, mo_time % 60);
            }
        } else if (mo_time > 90) {
            if (isWholeHour) {
                System.out.printf("\nLawn area = %.0f m2\n\nMowing time %.0f hour\n\nTime to purchase a new lawnmower", area, mo_time / 60);
            } else {
                System.out.printf("\nLawn area = %.0f m2\n\nMowing time %.0f hour %.0f mins \n\nTime to purchase a new lawnmower", area, mo_time / 60, mo_time % 60);
            }
        }
        key.close();
    }
}

关键修改说明

  1. 向上取整实现:用Math.ceil()分别处理面积和修剪时间,替代原有的直接计算,确保满足向上取整需求
  2. 浮点数相等判断:用Math.abs(mo_time % 60) < 0.0001替代==,避免浮点数精度误差导致的判断失效
  3. 嵌套逻辑调整:将整小时的判断逻辑移到对应时间区间的else if内部,确保逻辑正确执行,同时保留原代码的区间划分风格

内容的提问来源于stack exchange,提问作者Chip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:07:29