复利计算器没有给我正确的数据?

时间:2017-10-15 04:20:17

标签: java

我有一个复利计算器,但是当我运行代码并在它要求时输入以下数字:

校长:10000 比率:0.02 年:10

并选择已设置的“年度”,以便如果我或用户输入该特定字符串,则选择变量将自动变为1(或者如果我输入单词Quarterly或Monthly,则已设置的其他值)。但是,我应该得到一个值:$ 12189.94而我得到的值是:10200.0 我的代码在哪里出错?

import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {

public static void main (String [] args)
        { 
            Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;

System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();

 System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();

System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();

System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();

 System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();

 if ("Annual".equalsIgnoreCase(quest))
{ choice =1;

 }
 else if ("Quarterly".equalsIgnoreCase(quest)){
     choice = 4;
 }
 else if ("Monthly".equalsIgnoreCase(quest)){
     choice = 12;
 }
 else {
     choice = 0;
     System.out.println("Please choose a investment plan or speak to a financial advisor.");
 }

saving = principal*(1+(rate/choice))*Math.pow(choice,years);
System.out.println(saving);

2 个答案:

答案 0 :(得分:1)

感谢大家提供建议。我似乎需要使用:

saving = principal * Math.pow(1+(double) (rate/ (choice)), choice * years);

为了使我的等式工作,因为我的等式似乎没有正确地考虑我的整数值,因为保存被归类为双精度。

答案 1 :(得分:0)

您计算利息的公式不正确。它应该是:

saving = principal*Math.pow(1+(rate/choice), choice*years);

请在此处查看正确的公式:https://en.wikipedia.org/wiki/Compound_interest#Periodic_compounding