gpt4 book ai didi

java - 代码错误 - Java 储蓄账户

转载 作者:行者123 更新时间:2023-11-29 05:14:17 24 4
gpt4 key购买 nike

有一个输出困惑,将我所有的余额转换为 0.000000

这是我的代码:

package savingsaccountclass;

import java.util.Scanner;

public class SavingsAccountClass
{
public static void main(String[] args)
{
double annualInterestRate;
double savingsBalance;
double[] postInterestBalance = new double[100];
int counter = 0;

Scanner entry = new Scanner(System.in);

System.out.println("Enter the current annual interest rate");
annualInterestRate = entry.nextDouble();

System.out.println("Enter the current balance.");
savingsBalance = entry.nextDouble();

while (counter < 12)
{
postInterestBalance[counter] = calculateMonthlyInterest(savingsBalance, annualInterestRate);
System.out.printf("After Month %d. %f\n", counter + 1, postInterestBalance[counter]);
counter++;
}
}

public static double calculateMonthlyInterest(double balance, double interest)
{
double[] array = new double[100];
int c = 0;
double done = (balance * (interest/12));
while (c < 12)
{
array[c] = (((c + 1) * done) + balance);
c++;
}
return array[c];
}
}

这是我的输出:

run:
Enter the current annual interest rate
1
Enter the current balance.
100
After Month 1. 0.000000
After Month 2. 0.000000
After Month 3. 0.000000
After Month 4. 0.000000
After Month 5. 0.000000
After Month 6. 0.000000
After Month 7. 0.000000
After Month 8. 0.000000
After Month 9. 0.000000
After Month 10. 0.000000
After Month 11. 0.000000
After Month 12. 0.000000
BUILD SUCCESSFUL (total time: 1 second)

如果有人能告诉我为什么所有内容都转换为 0,我将不胜感激。谢谢:)

最佳答案

您正在填写数组中的前 12 余额,但您返回的是 array[12],它从未被赋值,所以它是 0.

Return array[c - 1] 返回数组最后填充的元素。

此外,您的利率 1 被解释为 100%,即每月增加 100/12 或 8 1/3 %。将利率除以 100 以将百分比转换为所需的小数。

此外,您目前并未计算复利。您目前正在计算初始余额 100 上每个“月”的当前利息。相反,您需要根据上个月的余额而不是初始余额计算每月利息,使用 array[c - 1] 访问上个月的余额。

关于java - 代码错误 - Java 储蓄账户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27137654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com