0

I have to make an application that calculates the compound interest per month. The principal is $1000, and the rate is 2.65%. I have attempted to code the application and succeeded in some areas. However, I am having problems with the actual math and have tried different ways to get the compound interest with no success. The link is pasted below. Any help would be appreciated, thank you.

http://pastebin.com/iVaWHiAJ

import java.util.Scanner;

class calculator{

private double mni, mni2, mni3;
private double intot = 1000;
private int a, c;

        double cinterest (int x){
                for(a=0;a<x+1;a++){
                        mni = intot * .0265;
                        intot = mni + intot;
                        //mni3 = (intot - mni) - 1000;
                        mni3 = (intot - mni);

                }
                return(mni3);
        }
}

class intcalc{

        public static void main(String[] args){

                calculator interest = new calculator();
                Scanner uinput = new Scanner(System.in);
                int months[] = {2, 5, 10, 500};
                int b;

                        for(b=0;b<4;b++){
                                System.out.println("Interest at " +
                                months[b] + " months is: " + interest.cinterest(months[b]));

                        }

        }

}
4

2 回答 2

3

它比那更简单。首先,您可以使用 Math.pow 而不是循环来进行复合。在这种情况下,最简单的做法就是使用静态方法:

public class CalcInterest{

  public static double getInterest(double rate, int time, double principal){
    double multiplier = Math.pow(1.0 + rate/100.0, time) - 1.0;
    return multiplier * principal;
  }

  public static void main(String[] args){
    int months[] = {2, 5, 10, 500};
    for(int mon : months)
        System.out.println("Interest at " + mon + " months is " + getInterest(2.65,mon,1000));

  }

}

这是输出:

Interest at 2 months is 53.70224999999995
Interest at 5 months is 139.71107509392144
Interest at 10 months is 298.94133469174244
Interest at 500 months is 4.7805288652022874E8
于 2013-09-23T22:26:59.363 回答
1

你应该更多地阅读复利背后的数学知识。是计算复利的简单指南。阅读并理解后,您应该使您的cintrest代码看起来像 -

double cintrest(int x){
    return intot - (intot(1+.0265)^x);
}

我在这里使用您的命名约定,但您确实需要取一些更好的名称。

于 2013-09-23T20:14:40.973 回答