修复Python 3.6利息计算代码错误,实现预期复利计算结果
Hey there! Let's get that interest calculator working exactly as you expect. The core issue with your current code is that it's calculating simple interest instead of compound interest—which is why your output numbers don't match what you're aiming for. Compound interest earns interest on both the initial principal and the accumulated interest from previous periods, which is what your expected results show.
First, let's break down the problems in your original code:
- You initialized
money=0instead of starting with the initial principal amount - Your interest formula uses the original principal every year (
i_amount*(anual_rate/100)*i) which calculates simple interest, not compound - Input prompts don't match the text in your expected output
- Output formatting has minor issues (missing pluralization for "years" and unrounded growth percentage)
Here's the fixed code that produces your desired results:
def interest_calculator(): print("Enter the following details.") i_amount = float(input('Your initial amount : ')) num_yr = int(input('Number of years : ')) anual_rate = float(input('Annual interest rate (as a percentage ): ')) # Start with the initial principal for compound interest calculations money = i_amount for i in range(1, num_yr + 1): # Update the amount using compound interest: each year's value is previous amount * (1 + annual rate) money = money * (1 + anual_rate / 100) # Handle pluralization for "year/years" in output year_label = "year" if i == 1 else "years" print(f'Money after {i} {year_label} is {round(money, 2)}') # Calculate and format the total growth percentage growth_percent = ((money - i_amount) / i_amount) * 100 print(f'Money growth after {num_yr} years is (as a percentage) {round(growth_percent, 2)}')
Key Changes Made:
- Added initial prompt: Matched the expected opening text "Enter the following details."
- Fixed starting principal: Set
money = i_amountso we begin compounding from the original investment - Compound interest formula: Replaced the simple interest calculation with
money = money * (1 + anual_rate / 100)—this updates the principal each year to include earned interest - Pluralization fix: Used a ternary operator to display "year" for 1 period and "years" for multiple periods
- Safer input handling: Used
float()andint()instead ofeval()(avoids security risks from arbitrary code execution) - Cleaner output formatting: Used f-strings for readable printing, and rounded all values to 2 decimal places to match your expected results
When you run this code, you'll get exactly the output you wanted:
interest_calculator ()
Enter the following details .
Your initial amount : 5000
Number of years : 5
Annual interest rate ( as a percentage ): 2.35
Money after 1 year is 5117.5
Money after 2 years is 5237.76
Money after 3 years is 5360.85
Money after 4 years is 5486.83
Money after 5 years is 5615.77
Money growth after 5 years is (as a percentage) 12.32
内容的提问来源于stack exchange,提问作者user9276239

