打印最终金额
在这最后一步中,你将通过添加格式化输出并改进财务结果的呈现方式来增强复利计算程序。
让我们修改之前的程序以改进结果格式化:
cd ~/project
nano compound_interest.c
用增强的输出格式化更新程序:
#include <stdio.h>
#include <math.h>
int main() {
// 声明本金、利率、时间、金额和利息的变量
float principal, rate, time, amount, interest;
// 提示并读取本金金额
printf("复利计算器\n");
printf("----------------------------\n");
printf("输入本金金额:");
scanf("%f", &principal);
// 提示并读取年利率
printf("输入年利率(以百分比表示):");
scanf("%f", &rate);
// 提示并读取时间段
printf("输入时间段(以年为单位):");
scanf("%f", &time);
// 将利率转换为小数
rate = rate / 100;
// 计算复利
amount = principal * pow(1 + rate, time);
interest = amount - principal;
// 打印格式化的财务结果
printf("\n===== 财务计算结果 =====\n");
printf("初始本金: $%10.2f\n", principal);
printf("年利率: %10.2f%%\n", rate * 100);
printf("投资期限: %10.2f年\n", time);
printf("-------------------------------------------\n");
printf("最终金额: $%10.2f\n", amount);
printf("赚取的总利息: $%10.2f\n", interest);
printf("==========================================\n");
return 0;
}
编译程序:
gcc compound_interest.c -o compound_interest -lm
运行程序:
./compound_interest
示例输出:
复利计算器
----------------------------
输入本金金额:1000
输入年利率(以百分比表示):5
输入时间段(以年为单位):3
===== 财务计算结果 =====
初始本金: $ 1000.00
年利率: 5.00%
投资期限: 3.00年
-------------------------------------------
最终金额: $ 1157.63
赚取的总利息: $ 157.63
==========================================
解释
- 添加了更具描述性的标题和分隔符
- 使用
%10.2f
格式说明符进行对齐的、固定宽度的小数输出
- 单独计算利息以使其呈现更清晰
- 包含一个标题并以结构化方式显示财务结果