公式Python中的负数

时间:2018-11-10 00:24:13

标签: python

因此,我正在为我的计算机科学课编写一个贷款计算器程序,但遇到了麻烦。在用于计算总付款额的公式中,它具有负数。我不知道如何解决它。我仍然必须添加一个while循环,这样程序才刚刚结束。到目前为止,这是我的程序:

import math
# Returns the number of payments per year
def get_payments_per_year(frequency):
    if frequency == "a":
        return 1
    elif frequency == "s":
        return 2
    elif frequency == "q":
        return 4
    elif frequency == "m":
        return 12
    elif frequency == "d":
        return 365

# Loan calculation functions removed; don't get called after the error.

# main
another = "Y"
amount = int(input("Enter amount of loan: "))
annual_ir = int(input("Enter annual interest rate: "))
payoff_yrs = int(input("Enter payoff period in years: "))

print("How frequently will you pay?")
frequency = input("[a]nnually \ [s]emi-annually \ [q]uarterly \ [m]onthly \ [d]aily? ")
payment_count = get_payments_per_year(frequency)

dec_annual_ir = annual_ir / 100
per_int_rate = dec_annual_ir / payment_count
total_pay_count = frequency * payoff_yrs
total_pay = (per_int_rate * amount) / (1 - (math.pow((1 + per_int_rate),-total_pay_count)))
# Code after this point isn't executed.

它返回此错误:

Traceback (most recent call last):
line 81, in <module>
    total_pay = (per_int_rate * amount) / (1 - (math.pow((1 + per_int_rate),-total_pay_count)))
TypeError: bad operand type for unary -: 'str'

1 个答案:

答案 0 :(得分:0)

是的,您在-total_pay_count中进行了非法操作。查看数据流:

payoff_yrs = int(input("Enter payoff period in years: "))
frequency = input("[a]nnually \ [s]emi-annually \ [q]uarterly \ [m]onthly \ [d]aily? ")
total_pay_count = frequency * payoff_yrs

total_pay_count是一个字符串。对于我30年的每月贷款,这是一串30'm's。我想你要

payment_count = get_payments_per_year(frequency)
total_pay_count = payment_count * payoff_yrs