如何修复for循环生成发车时间序列的错误?实现正确的20分钟递增
Fixing Train Departure Time Loop with Correct Hour Carryover
Let's break down what's going wrong with your current code first, then fix it with a cleaner, more reliable approach.
What's Broken in the Original Code
Your logic has a few key issues that lead to broken time outputs like 15:-4:
- You're printing twice per loop iteration, which creates duplicate or unexpected entries
- The
breakstatement stops the loop entirely when minutes hit 60 instead of carrying over to the next hour - The minute calculation after attempting to carry over (
m = m-60+20) is out of order, leading to negative values when the timing math doesn't line up
The Fix: Use Total Minutes for Clean Carryover
Instead of manually adjusting hours and minutes separately, convert everything to total minutes since midnight, add your 20-minute interval, then convert back to hours and minutes. This eliminates all edge cases with negative minutes or missed carryovers.
Here's the corrected code:
h = 13 m = 36 # Adjust range(5) if you want more/less departure times for _ in range(5): # Format minutes to 2 digits so times like 15:6 show as 15:06 print(f"The train will leave at {h}:{m:02d}") # Calculate total minutes since midnight, add 20 minutes for the next interval total_minutes = h * 60 + m + 20 # Convert back to hours and minutes (auto-handles carryover) h = total_minutes // 60 m = total_minutes % 60
How This Works
- Initialization: Start with your base time (13:36)
- Print: Output the current formatted time (using
:02densures minutes are always two digits for proper time formatting) - Total Minutes Calculation: Convert hours to minutes, add the current minutes, then add 20 for the next departure interval
- Convert Back: Use integer division (
//) to get the new hour count, and modulus (%) to get the remaining minutes—this automatically handles carryover when minutes exceed 60
Sample Output
Running this code will produce:
The train will leave at 13:36 The train will leave at 13:56 The train will leave at 14:16 The train will leave at 14:36 The train will leave at 14:56
If you extend the loop, it will correctly output The train will leave at 15:16 next, with no negative minutes or broken logic.
内容的提问来源于stack exchange,提问作者vectorizinglife
相关产品推荐
相关产品推荐

