PHP实现按分钟计算停车时长收费功能的技术咨询
Fixing Your Parking Fee Calculation Function
Hey there! Let's get your parking fee calculator working reliably for any duration, not just the first two hours. First, let's break down the gaps in your current code:
- It hardcodes the parking time as 10 minutes, so it can't handle different input values.
- It only accounts for durations under 2 hours—anything over 120 minutes will throw an error because
$time_parkedisn't defined in that case. - The
returnstatements inside yourif/elseifblocks mean the finalecholine will never run (the function exits before reaching it).
Here's the Improved Solution
Based on your requirements:
- $50 for 1 hour (or less)
- $100 for the 1–2 hour interval
- $200 for 2–3 hours, and so on (each additional hour interval doubles the fee)
We can create a reusable, dynamic function that handles all scenarios:
function calculateParkingFee(int $minutes): float { $baseRate = 50.0; // Ensure we use at least 1 interval (even for 0 minutes, per your "1 hour (含)以内" rule) $hourIntervals = max(1, ceil($minutes / 60)); // Calculate fee: each interval after the first doubles the base rate $totalFee = $baseRate * (2 ** ($hourIntervals - 1)); echo "Amount to pay: $" . number_format($totalFee, 2) . "\n"; return $totalFee; } // Test with different parking durations calculateParkingFee(10); // Output: Amount to pay: $50.00 calculateParkingFee(60); // Output: Amount to pay: $50.00 calculateParkingFee(61); // Output: Amount to pay: $100.00 calculateParkingFee(120); // Output: Amount to pay: $100.00 calculateParkingFee(121); // Output: Amount to pay: $200.00 calculateParkingFee(240); // Output: Amount to pay: $400.00 calculateParkingFee(0); // Output: Amount to pay: $50.00
Key Details Explained:
- Parameterized Input: The function accepts
$minutesas an argument, so you can pass any parking duration instead of hardcoding it. - Interval Calculation:
ceil($minutes / 60)rounds up minutes to the next full hour interval (e.g., 61 minutes becomes 2 intervals for the 1–2 hour window). Usingmax(1, ...)ensures even 0 minutes uses the 1-hour interval rule. - Doubling Logic:
2 ** ($hourIntervals - 1)handles the fee doubling: for 1 interval, it’s2^0 = 1($50), for 2 intervals it’s2^1 = 2($100), and so on. - Clean Currency Output:
number_format()formats the fee to two decimal places, matching standard currency display.
内容的提问来源于stack exchange,提问作者Leandro Matilla
相关产品推荐
相关产品推荐

