是否可以使用JOptionPane通过输入找到Java的复利?

问题描述 投票:0回答:2

我尝试了以下输入:

主要= 1000,比率= 4,应用次数= 2(半年),经过的年= 2

import javax.swing.*;
import java.math.BigDecimal;

public class CICalc {
    public static void main(String[] args) {
        Double principal;
        Double rate;
        Double timesapplied;
        Double elapsedyears;

        principal= Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
        rate=Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
        timesapplied=Double.parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
        elapsedyears=Double.parseDouble(JOptionPane.showInputDialog("Enter the amount of time(In years and if in months, write them in this format- month/12) the principal is being invested for"));

        BigDecimal CI;
        BigDecimal inf;
        inf= BigDecimal.valueOf(Math.pow(rate+(1/timesapplied*100),elapsedyears*timesapplied));

        CI= (BigDecimal.valueOf(principal)).multiply(inf);
        BigDecimal P= CI.subtract(BigDecimal.valueOf(principal));

        JOptionPane.showMessageDialog(null,"The Compound Interest for "+elapsedyears+" years is "+CI+"$ and the the interest gained is "+P+"$");

    }
}

有人可以指出错误并帮助我吗?实际上,我仅使用Double进行了设置,但问题是结果的小数点太多。所以我不得不使用BigDecimal

java joptionpane
2个回答
0
投票

我认为您应该避免使用Double,而应使用BigDecimal。

您甚至可以在此行中使用BigDecimal

principal= new BigDecimal(JOptionPane.showInputDialog("Enter the principal amount"));

两次操作不会给出准确的精确结果。如果您需要精度,请使用BigDecimal


0
投票
    // for $200, at .25%, compounded 2 times, for twelve months ...

    Double inf2 = rate+(1/timesapplied*100); // I get 50.25 for this computation.
    System.out.println(inf2);
    Double inf3 = elapsedyears*timesapplied;  // I get 24.0 for this computation.
    System.out.println(inf3);
    Double inf4 = Math.pow(inf2,inf3); // Really? 50, raised to the power of 24 ???
    System.out.println(inf4);

这会产生很大的数字。您是否不需要在年金公式的某处除以负1?那数学不对。问题来自您的战俘。

© www.soinside.com 2019 - 2024. All rights reserved.