我想四舍五入到最接近的半小时,这意味着如果我在11:15到达,11:50离开,汽车仍将收取一个半小时而不是两个小时的费用

2024-09-27 00:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想四舍五入到最接近的半小时,这意味着如果我在11:15到达,11:50离开,汽车仍将收取一个半小时而不是两个小时的费用。在过去的几个小时里,我一直试图修复它,但我似乎不知道该怎么做(我最近开始学习编程)

import math
PARKING_COST = 1.75
TAX_RATE = 1.13
startHour = eval(input('Input the hour when you entered the parking lot(in 24h time please, no leading zeroes):'))
startMinute = input('Input the minute when you entered the parking lot: ')
endHour = eval(input('Input the hour when you exited the parking lot(in 24h time please, no leading zeroes): '))
endMinute = input('Input the hour when you exited the parking lot: ')
minutesPassed = (60*endHour + int(endMinute))-(60*startHour + int(startMinute))

k=1
if minutesPassed<=(15*k):
    k+=1
    halfHoursPassed=math.floor(float(minutesPassed)/30)
else:
    halfHoursPassed=math.ceil(float(minutesPassed)/30)


subtotal = halfHoursPassed * 1.75
total = subtotal * 1.13

print('*******')
print('Parkinglot')
print('Your time in was',str(startHour)+':'+ startMinute)
print('Your time out was',str(endHour)+':'+ endMinute)
print('You spent','%.0f' %halfHoursPassed,'half hours at our garages')
print('Your subtotal was $' + '%.2f' %subtotal)
print('Your total was $' + '%.2f' %total)
print('Thank you for your stay')
print('*******')

Tags: theyouinputyourtimelotwhenprint
2条回答

因此,使用full_halves = int(minutesPassed / 30)可以获得“完整”的30分钟周期。然后使用模运算符%得到余数:remaining = minutesPassed % 30。现在,如果这个remainer大于15,您应该再添加一个完整的一半,否则您将按原样使用full_halves

模运算符%返回地板除法//后的余数。也就是说7 // 3 == 2, 7 % 3 == 1。事实上,这两者是相互定义的,因此(x // k) * k + (x % k) == x

你应该考虑取你的^ {< CD5>}和30的模,看看部分半小时在哪里,然后与15比较,判断是否上下。p>

halfHoursPassed = minutesPassed // 30
if minutesPassed % 30 >= 15:
    halfHoursPassed += 1

通过使用内置的divmod,可以在某种程度上简化这一点,它同时提供//%

halfHoursPassed, partialHalfHour = divmod(minutesPassed, 30)
if partialHalfHour >= 15:
    halfHoursPassed += 1

相关问题 更多 >

    热门问题