我遇到了问题
前3个小时的停车费为每小时3美元,每增加一小时,您需要支付1美元,24小时的费用为30美元,但您可以停留超过24小时。 我不知道如何解决小时> 24,就像汽车停留37小时或更长时间一样。我认为必须使用模数,不幸的是我无法使用它。任何帮助??
if (hours >= 24) {
price = 30;
price += (hours - 3) % 1; //should the mod even go here?
} else if (hours < 24 && hours > 3) {
price = 9;
price += (hours - 3) * 1;
} else {
price = hours * 3;
}
System.out.println("Hours: " + hours + " Price: " + price);
答案 0 :(得分:3)
根据您的规范,它应该像以下一样简单:
price = Math.min(hours, 3) * 3 + Math.max(hours - 3, 0) * 1;
System.out.println("Hours: " + hours + " Price: " + price);
更新
price = (hours / 24) * 30 + Math.min(hours % 24, 3) * 3 + Math.max(hours % 24 - 3, 0) * 1;
答案 1 :(得分:1)
这有效:
if (hours >= 24) {
price = (hours / 24)*30;
int h = hours%24;
int h4 = Math.min(h, 3)*2;
price += h4 +((hours)%24);
} else if (hours < 24 && hours > 3) {
price = 9;
price += (hours - 3) * 1;
} else {
price = hours * 3;
}
System.out.println("Hours: " + hours + " Price: " + price);
答案 2 :(得分:1)
修改@ bohuss的解决方案以解决问题超过24小时:
private static int calculatePrice(final int hours) {
// find number of days [where 1 day is 24 hours]
final int days = hours / 24;
// calculate price based on 1 day's fixed price as $30
int price = 30 * days;
// find remaining hours
final int remainingHours = hours % 24;
// calculate price for remaining hours and add to price for entire days.
price += Math.min(remainingHours, 3) * 3 + Math.max(remainingHours - 3, 0) * 1;
// return total price
return price;
}
示例输入/输出
Hours: 0 Price: 0 Hours: 1 Price: 3 Hours: 2 Price: 6 Hours: 3 Price: 9 Hours: 4 Price: 10 Hours: 5 Price: 11 Hours: 6 Price: 12 ... Hours: 22 Price: 28 Hours: 23 Price: 29 Hours: 24 Price: 30 Hours: 25 Price: 33 Hours: 26 Price: 36 Hours: 27 Price: 39 Hours: 28 Price: 40
答案 3 :(得分:0)
if(hours > 0) {
if(hours > 3 && hours < 24) {
price = 3 + hours;
}
if(hours >= 24) {
price = 30;
}
}
请注意,如果停车的人员在24小时后仍然按每小时1美元收费,那么:
if(hours > 0) {
if(hours > 3 && hours < 24) {
price = 3 + hours;
}
if(hours >= 24) {
price = 30 + hours - 24;
}
}