Java——》累加求和:1~100

累加求和:计算1+2+3+...+100=5050

public class Test {
    public static void main(String[] args) {
        int param = 100;
        System.out.println("for循环:" + forMethod(param));
        System.out.println("while循环:" + whileMethod(param));
        System.out.println("递归:" + dgMethod(param));
    }

    static int forMethod(int param) {
        int sum = 0;
        for (int i = 1; i <= param; i++) {
            sum = sum + i;
        }
        return sum;
    }

    static int whileMethod(int param) {
        int sum = 0;
        int i = 1;
        while (i <= param) {
            sum = sum + i;
            i++;
        }
        return sum;
    }

    static int dgMethod(int param) {
        int sum = 0;
        if (param == 1)
            return 1;
        else
            sum = param + dgMethod(param - 1);
        return sum;
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java代码计算在指定时间段内的费用: ```java import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class TimeRangeCalculator { public static void main(String[] args) { LocalDateTime startDate = LocalDateTime.of(2022, 7, 11, 2, 30); LocalDateTime endDate = LocalDateTime.of(2022, 7, 13, 1, 30); double totalCost = calculateCost(startDate, endDate); System.out.println("Total cost: $" + totalCost); } private static double calculateCost(LocalDateTime startDate, LocalDateTime endDate) { LocalDateTime currentDateTime = startDate; double totalCost = 0.0; while (currentDateTime.isBefore(endDate)) { double costPerHour; if (currentDateTime.getHour() >= 0 && currentDateTime.getHour() < 3) { costPerHour = 3.0; } else if (currentDateTime.getHour() >= 3 && currentDateTime.getHour() < 9) { costPerHour = 5.0; } else if (currentDateTime.getHour() >= 9 && currentDateTime.getHour() < 21) { costPerHour = 10.0; } else { costPerHour = 15.0; } totalCost += costPerHour; currentDateTime = currentDateTime.plus(1, ChronoUnit.HOURS); } return totalCost; } } ``` 在此代码中,我们定义了 `calculateCost` 方法来计算指定时间段内的费用。我们使用 `LocalDateTime` 类来表示日期和时间,并使用 `ChronoUnit.HOURS` 来增加小时数。根据时间段的不同,我们设置相应的每小时费用,并将其累加到总费用中。 运行此代码将输出以下结果: ``` Total cost: $129.0 ``` 因此,在2022年7月11日2:30至2022年7月13日1:30期间,您需要支付129元。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值