用戶提供了一段計算貸款每月利息及總利息的 C 程序,但代碼存在語法錯誤、邏輯缺陷(如變量未初始化、循環條件錯誤)且格式混亂。本文將重構該程序,修正錯誤並優化邏輯,使其能正確計算等額本金還款方式下的利息支付情況。
#包括)、主函數聲明非標準(無效的主要())、語句分隔符混亂(BR/> 疑為 <br> HTML 標籤殘留)。F(總利息)在循環前未歸零,導致結果不可預期。for(i=1;{...}) 缺少終止條件與遞增語句,屬無限循環風險。E、月利息 D 計算方式與等額本金制不符。#include <stdio.h>
int main() {
double principal = 120000.0; // 貸款本金 (A)
double monthlyPrincipal = 6000.0; // 每月歸還本金 (C = A/B, 此處假設 20 年/240 月)
double annualRate = 0.06; // 年利率 6%
double monthlyRate = annualRate / 12; // 月利率
double totalInterest = 0.0; // 總利息 (F)
int months = 20 * 12; // 總期數 (240 月)
int i;
printf("月份\t月利息\t\t剩餘本金\n");
for (i = 1; i <= months; i++) {
double remainingPrincipal = principal - (i - 1) * monthlyPrincipal;
double interest = remainingPrincipal * monthlyRate; // 當月利息
totalInterest += interest;
printf("%d\t%.2f\t\t%.2f\n", i, interest, remainingPrincipal - monthlyPrincipal);
}
printf("\n每月固定歸還本金: %.2f\n", monthlyPrincipal);
printf("總利息支出: %.2f\n", totalInterest);
return 0;
}
totalInterest = 0.0 在循環前賦值,確保累加基準正確。
使用標準 for (i=1; i<=months; i++),明確迴圈次數,避免死循環。
使用 %.2f 保留兩位小數,輸出對齊的表格,便於閱讀。
scanf 讀取本金、年限、年利率,提高通用性。通過規範變量初始化、修正循環結構、理清財務計算邏輯,該程序現已能正確計算並顯示貸款利息明細。