【问题标题】:Compound Interest calculator isn't giving me correct data?复利计算器没有给我正确的数据?
【发布时间】:2017-10-15 04:20:16
【问题描述】:

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

本金:10000 率:0.02 年:10

并选择已经设置好的“Annual”,这样如果我或用户输入该特定字符串,则选择变量将自动变为 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);

【问题讨论】:

    标签: java


    【解决方案1】:

    感谢大家提供建议。看来我需要使用:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 我使用的公式是我的教授为我必须创建的这段代码提供的,也是我必须专门使用的。另外,我事先用手和计算器检查了它,得到了我应该得到的值。但是当我运行代码时,不会产生特定的结果。
      • 您可能错误地执行了教授的公式。您示例中的代码正在计算:10000*(1+(0.02/1))*(1^10) = 10200。你想做10000*((1+(0.02/1))^(1*10)) = 12189。试试我提供的代码,看看它是否有效。
      • 试过了,但它仍然给我错误的输出。
      • 你得到了什么输出?我刚刚对其进行了测试,它给出了您想要的确切输出。
      • 我仍然得到 10200.0 的输出
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多