java - 简单的 Java 现值计算器不工作

标签 java

我以前没有使用过 java,我很困惑为什么我写的一个简单的现值计算器不起作用。由于某种原因,现值公式返回一个超小数字?看看你是否能发现我的错误:

// Import all utilities
import java.text.DecimalFormat;
import java.util.*;

// Base class
public class Project2
{

   // Main function
   public static void main(String[] args)
   {
      // Define variables
      double p = 0.0;
      double f = 0.0;
      double r = 0.0;
      double n = 0.0;
      String another = "Y";

      // Create a currency format
      DecimalFormat dollar = new DecimalFormat("#,###.00");

      // Create a new instance of the scanner class
      Scanner keyboard = new Scanner(System.in);

      // Loop while another equals "Y"
      while(another.equals("Y"))
      {
         // Get future value
         System.out.println("Future value: ");
         f = Double.parseDouble(keyboard.nextLine());

         // Get annual interest rate
         System.out.println("Annual interest rate: ");
         r = Double.parseDouble(keyboard.nextLine());

         // Get Number of years
         System.out.println("Number of years: ");
         n = Double.parseDouble(keyboard.nextLine());

         // Run method to find present value and display result
         p = presentValue(f, r, n);
         System.out.println("Present value: $" + p );

         // Ask if user wants to enter another
         System.out.println("Enter another?(Y/N) ");
         another = keyboard.nextLine().toUpperCase();
      }

   }

   public static double presentValue(double f, double r, double n)
   {
      // Do math and return result
      double p = f / Math.pow((1 + r), n);
      return p;
   }
}

最佳答案

假设您将 R 输入为 % per annum 即例如R = 4.3%,您可能希望将函数修改为:

double p = f / (Math.pow((1 + (r/100.0)), n));
return p;

如果这不是您想要的,您可能需要将 R=4.3% p.a 的值输入为

4.3/100 = 0.043 而不是 4.3

关于java - 简单的 Java 现值计算器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486277/

相关文章:

java - MongoDB - 如何在不定义键的情况下访问值字段

java - 如何模拟这个创建kafka主题并等待 future 对象的简单方法?

java - 转到最近使用的内容并返回时显示错误的 fragment

java - 如何在不同的 Eclipse 项目之间共享资源,以避免重复?

java - 命令输出解析

Java如何将UK转换为java.util.Date

java - 在运行时替换字段的类(用于 protostuff)

java - 从资源文件夹中读取文件,在 Spring Boot 应用程序中始终给出 Inputstream 为空的情况

java - MongoDB Multi-Tenancy (Java): How to switch MongoDB databases,在运行时使用MongoClient具有不同的数据库凭据?

java - 从服务器应用程序连接到 FCM 时获取 "Server returned HTTP response code: 400"