代码的输入是枚举:
public enum Family
{
WILMA("Wilma", "Flintstone", 5000, 0.05, 10, 35),
FRED("Fred", "Flintstone", 15000, 0.075, 7, 30),
BETTY("Betty", "Rubble", 7500, 0.0375, 10, 25),
BARNEY("Barney", "Rubble", 5000, 0.09, 10, 35);
private final String firstName;
private final String lastName;
private final double annualDeposit;
private final double annualInterest;
private final int yearsDeposit;
private final int compoundCalcYr;
}
代码的其他部分是getter,setter和printf&#39。
对于这个程序,我随着时间的推移计算复利。为了舍入,我需要为我的所有计算使用BigDecimal数据类型。
第一次运行后循环不正确:
第1年:存款为5000.0,收入为$ 5,250.00。 第2年:存款为10000.0,收入为11,025.00美元
但是,第2年应该存入10000.0并且 10762.5获得。
这是我的数学似乎不正确的代码。
for (Family family : Family.values()) // From here onward
{
BigDecimal principal = BigDecimal.valueOf(family.getAnnualDeposit());
BigDecimal rate = BigDecimal.valueOf(family.getAnnualInterest());
BigDecimal annualDeposit = BigDecimal.valueOf(family.getAnnualDeposit());
for (int year = 1; year <= family.getCompoundCalcYr(); year++)
{
BigDecimal amount = principal.multiply(rate.add(BigDecimal.ONE).pow(year));
if (year <= 1) //Used as a header only
{
System.out.printf("\n%s %s\n", family.getFirstName(), family.getLastName());
}
System.out.printf("Year %d: ", year, family.getFirstName());
System.out.printf("Deposited: %s", principal);
System.out.printf("\t\tEarned: %s\n", NumberFormat.getCurrencyInstance().format(amount));
BigDecimal earned = amount;
if (year <= family.getYearsDeposit())
{
//earned = earned.add(annualDeposit); // earned = 5250 deposited should be 10k
principal = principal.add(annualDeposit); //second run 10k
}
对于正确方向的任何帮助表示赞赏,谢谢。