Когда я использую "% .2f", я получаю сообщение об ошибке "float требуется", почему? - PullRequest
0 голосов
/ 25 марта 2019

Я делаю проект для школы, и в конце я должен подвести итог счета клиента (пользователя).

Если я удалю «% .2f», я не получу сообщение об ошибке, но отображаемое число будет продолжаться и продолжаться.Как отобразить только последние 2 десятичных знака?

Код, который я использую:

print('Amount Due:        $' + '%.2f' % baseCharge)

Вывод, который я получаю:

    print('Amount Due:        $' + '%.2f' % baseCharge)
TypeError: a float is required

Весь код:


rentalCode = input("(B)udget, (D)aily, or (W)eekly rental?\n")

weeksRented = 0
daysRented = 0
budgetCharge = 40
dailyCharge = 60
weeklyCharge = 190


if rentalCode == 'B' or rentalCode == 'D':
  daysRented = input("Number of Days Rented:") #Prompt --> "Number of Days Rented:"
else:
    weeksRented = input("Number of Weeks Rented:\n") #Prompt --> "Number of Weeks Rented:"

odoStart = int(input("Starting Odometer Reading:\n"))
odoEnd = int(input("Ending Odometer Reading:\n"))
totalMiles = odoEnd - odoStart

print(rentalCode) # Displays Chosen Rental Code
if rentalCode == 'B' or rentalCode == 'D': # Decides which option has been input and displays the output
  print(daysRented)
else:
  print(weeksRented)

baseCharge = 0
if rentalCode == 'B':
  baseCharge = daysRented * budgetCharge
elif rentalCode == 'D':
  baseCharge = daysRented * dailyCharge
elif rentalCode == 'W':
  baseCharge = weeksRented * weeklyCharge



#Print odoStart, odoEnd and totalMiles
print(odoStart)
print(odoEnd)
print(totalMiles)
# Calculate Charges 2

totalCharge = 0
if rentalCode == 'B':
  totalCharge = baseCharge + str(totalMiles * .25)
elif rentalCode == 'D':
  averageDayMiles = int(totalMiles) / int(daysRented)
  if averageDayMiles <= 100:
    totalCharge = baseCharge
  else:
    extraMiles = totalMiles - 100
    totalCharge = baseCharge + str(extraMiles * .25)
elif rentalCode == 'W':
  averageWeekMiles = int(totalMiles) / int(weeksRented)
  if averageWeekMiles <= 900:
    totalCharge = baseCharge
  else:
    totalCharge = baseCharge + str(weeksRented * 100)

print(totalCharge)

if rentalCode == "W":
    rentalPeriod = weeksRented
else:
    rentalPeriod = daysRented

print(rentalPeriod)

if rentalCode == "B":
    baseCharge = budgetCharge * rentalPeriod
elif rentalCode == "D":
    baseCharge = dailyCharge * rentalPeriod
else:
    baseCharge = weeklyCharge * rentalPeriod




print('Customer Summary')
print('Rental Code:       ' + rentalCode)
print('Rental Period:     ' + rentalPeriod)
print('Starting Odometer: ' + str(odoStart))
print('Ending Odometer:   ' + str(odoEnd))
print('Miles Driven:      ' + str(totalMiles))
print('Amount Due:        $' + '%.2f' % baseCharge)

Опять же, если этот% .2f находится на месте, я получаю ошибку вывода, но если я ее устраню, я получу большое число.Пример: вместо 951.65 я получу 951.6555555555555555555 и т. Д.

1 Ответ

0 голосов
/ 25 марта 2019
rentalCode = input("(B)udget, (D)aily, or (W)eekly rental?\n")

weeksRented = 0
daysRented = 0
budgetCharge = 40
dailyCharge = 60
weeklyCharge = 190


if rentalCode == 'B' or rentalCode == 'D':
  daysRented = int(input("Number of Days Rented:")) #Prompt --> "Number of Days Rented:"
else:
    weeksRented = int(input("Number of Weeks Rented:\n")) #Prompt --> "Number of Weeks Rented:"

odoStart = int(input("Starting Odometer Reading:\n"))
odoEnd = int(input("Ending Odometer Reading:\n"))
totalMiles = odoEnd - odoStart

print(rentalCode) # Displays Chosen Rental Code
if rentalCode == 'B' or rentalCode == 'D': # Decides which option has been input and displays the output
  print(daysRented)
else:
  print(weeksRented)

baseCharge = 0
if rentalCode == 'B':
  baseCharge = daysRented * budgetCharge
elif rentalCode == 'D':
  baseCharge = daysRented * dailyCharge
elif rentalCode == 'W':
  baseCharge = weeksRented * weeklyCharge



#Print odoStart, odoEnd and totalMiles
print(odoStart)
print(odoEnd)
print(totalMiles)
# Calculate Charges 2

totalCharge = 0
if rentalCode == 'B':
  totalCharge = baseCharge + (totalMiles * .25)
elif rentalCode == 'D':
  averageDayMiles = int(totalMiles) / int(daysRented)
  if averageDayMiles <= 100:
    totalCharge = baseCharge
  else:
    extraMiles = totalMiles - 100
    totalCharge = baseCharge + (extraMiles * .25)
elif rentalCode == 'W':
  averageWeekMiles = int(totalMiles) / int(weeksRented)
  if averageWeekMiles <= 900:
    totalCharge = baseCharge
  else:
    totalCharge = baseCharge + (weeksRented * 100)

print(totalCharge)

if rentalCode == "W":
    rentalPeriod = weeksRented
else:
    rentalPeriod = daysRented

print(rentalPeriod)

if rentalCode == "B":
    baseCharge = budgetCharge * rentalPeriod
elif rentalCode == "D":
    baseCharge = dailyCharge * rentalPeriod
else:
    baseCharge = weeklyCharge * rentalPeriod




print('Customer Summary')
print('Rental Code:       ' , rentalCode)
print('Rental Period:     ' , rentalPeriod)
print('Starting Odometer: ' , str(odoStart))
print('Ending Odometer:   ' , str(odoEnd))
print('Miles Driven:      ' , str(totalMiles))
print('Amount Due:        $' + '%.2f' % baseCharge)

Вот, пожалуйста. daysRented и weeksRented могут быть приняты как целые числа. Кроме того, вы можете объединять только строки, а не int в строку. Другое дело, что% .2f работает для вещественных чисел, а не для строк.
Вот пример вывода

(B)udget, (D)aily, or (W)eekly rental?
B
Number of Days Rented:2
Starting Odometer Reading:
100
Ending Odometer Reading:
150
B
2
100
150
50
92.5
2
Customer Summary
Rental Code:        B
Rental Period:      2
Starting Odometer:  100
Ending Odometer:    150
Miles Driven:       50
Amount Due:        $80.00
...