简体   繁体   中英

How to implement a particular maths formula in Java?

package methods;
import java.util.Scanner;

/**
*
* @author Billy
*/
public class Methods {

/**
 * @param args the command line arguments
 */
    public static void main(String[] args) {      
    double Loanamount; // Loan amount from user
    double Aintrate; // User's annual interest rate
    double months; // Number of months on loan
    double monp; // Monthly payment
    double Mintrate; // Monthly interest rate
    double n; // The number of payments


    // declare an instance of Scanner to read the datastream from the keyboard.
    Scanner kb = new Scanner(System.in);

    // Get user's loan amount
    System.out.print("Please enter your total loan amount: ");
    Loanamount = kb.nextDouble();

    // Get user's interest rate
    System.out.print("Please enter your annual interest rate as a decimal: ");
    Aintrate = kb.nextDouble();

    // Get user's number of months
    System.out.print("Please enter the number of months left on your loan: ");
    months = kb.nextDouble();

    // Calculate montly interest rate
    Mintrate = ((Aintrate / 12));

       System.out.println("Your monthly interest rate is " + " " + Mintrate);

    // Calculate number of payments
       n = ((months * 12));

    // Calculate monthly payment

My next job is to find out the monthly payment using this formula.

M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]

Where

M = monthly mortgage payment
P = The amount borrowed (Loanamount)
i = Monthly interest rate (Mintrate)
n = the number of payments

I tried the following but I just cant figure it out
monp = Loanamount [Mintrate(1+ Mintrate)^n] / [(1+ Mintrate)^n-1 ];

Math.pow is what you need instead of ^ . Also you can't use [ or ] . You have to use parenthesis ( and ) . More math functions can be found at: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

You need to use Math.pow effectivley here.

Try using following in your code

monp = Loanamount*(Mintrate*Math.pow((1+ Mintrate),n)) / (Math.pow((1+ Mintrate),n-1 ) ;

The method for ^ is called Math.pow(double a, double b); in Java.

Where a is the number to be raised b times.

Your formula would then look like monp = Loanamount Math.pow((Mintrate(1+ Mintrate), n)) / (Math.pow((1+ Mintrate), n-1));

Reference

You need to call Math.pow(double,double)

OR you could import the required class as..
import static java.lang.Math.pow;
and then use pow() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM