C++停车场计费程序开发求助:时长计算与收费逻辑实现
Great to hear you've already sorted out the time input conversion—let's jump right into building the fee calculation logic that matches your pricing rules. First, let's recap the rules to make sure we cover every edge case:
- Parking under 30 minutes: Free ($0)
- 30 minutes to 2 hours (inclusive): $3 base fee, plus 5 cents per minute for any time beyond the first 30 minutes
- Over 2 hours: $8 base fee, plus 10 cents per minute for any time beyond 2 hours
Step 1: Start with Total Parking Duration
Since you've already converted entry/exit times, we'll assume you have an integer variable total_minutes holding the total parking time in minutes. That's our core input for the calculation.
Step 2: Build the Fee Calculation Function
Here's a clean, readable function that applies the rules correctly and handles all boundary scenarios:
#include <iostream> #include <iomanip> // For proper currency formatting double calculateParkingFee(int total_minutes) { double fee = 0.0; if (total_minutes < 30) { // Under 30 minutes = no charge fee = 0.0; } else if (total_minutes <= 120) { // 30 mins to 2 hours: base $3 + 5c/min for time over 30 mins int extra_minutes = total_minutes - 30; fee = 3.0 + (extra_minutes * 0.05); } else { // Over 2 hours: base $8 + 10c/min for time over 2 hours int extra_minutes = total_minutes - 120; fee = 8.0 + (extra_minutes * 0.10); } return fee; }
Step 3: Test with Key Scenarios
Let's verify the function works for common edge cases:
- 25 minutes → $0.00 (correct, under 30 mins)
- 30 minutes → $3.00 (exact start of paid tier)
- 90 minutes → $3.00 + (60 * 0.05) = $6.00
- 120 minutes → $3.00 (exact end of the second tier)
- 130 minutes → $8.00 + (10 * 0.10) = $9.00
Step 4: Add Currency Formatting (Optional)
To output the fee as properly formatted currency, use std::fixed and std::setprecision to ensure two decimal places:
int main() { // Example usage: 2 hours 25 minutes = 145 minutes int parking_time = 145; double total_fee = calculateParkingFee(parking_time); std::cout << "Total Parking Fee: $" << std::fixed << std::setprecision(2) << total_fee << std::endl; // Outputs: Total Parking Fee: $10.50 return 0; }
This function is easy to tweak if your pricing rules change later, and the clear tier separation makes debugging a breeze.
内容的提问来源于stack exchange,提问作者Trev.Drumm

