2013-10-08 40 views
0

我正在爲我的介紹性Java編程課程開發一個項目,在那裏我必須創建一個計算用戶未來投資價值的程序。必須提示用戶在程序中有三件事:投資金額,年利率和投資年數。有了這些信息,程序就可以計算用戶的月利率反過來他們的未來投資價值。使用Math.pow方法

讓我們開始與我的教授未來的投資公式:

futureInvestmentValue = investmentAmount x (1 + monthlyInterestRate)^numberOfYears* 12 

其次,這是我到目前爲止的代碼:

public static void main(String[] args) { 
    // Create scanner objects for investmentAmount, numberOfYears, and annualInterestRate 
    Scanner investInput = new Scanner(System.in); 
    Scanner rateInput = new Scanner(System.in); 
    Scanner yearInput = new Scanner(System.in); 

    // Declare variables 
    int investmentAmount, numberOfYears; 
    double annualInterestRate, rate, monthlyRate, futureInvestmentValue; 

    // Create user inputs for investmentAmount, numberOfYears, and annualInterestRate 
    System.out.print("Please enter your investment amount: "); 
    investmentAmount = investInput.nextInt(); 

    System.out.print("Please enter your annual interest rate: "); 
    annualInterestRate = rateInput.nextInt(); 

    System.out.print("Please enter the number of years for your investment: "); 
    numberOfYears = yearInput.nextInt(); 

    // Variable assignments 
    rate = annualInterestRate/100; 
    monthlyRate = rate/12; 
    futureInvestmentValue = investmentAmount * (1.0 + monthlyRate); 

    //Output 
    System.out.print("Your annual interest rate is " + rate + 
     " and your monthly interest rate is " + monthlyRate); 

    investInput.close(); 
    rateInput.close(); 
    yearInput.close(); 
} 

我得到儘可能基於計算用戶的月息其輸入,並開始將我的教授公式翻譯成Java的語言。
但是,我無法弄清楚如何使用Math.pow方法來翻譯教授方程的指數部分。

+2

請刪除所有與'Math.Pow'部分無關的代碼以及所有與此無關的介紹性文本。我們不想知道整個任務;我們希望看到具體的問題是在少於5行的下面有相應的代碼。 –

+0

你是說你想知道調用'Math.pow'的語法嗎?或者你是否說你不知道該通過什麼?您可能會從http://stackoverflow.com/questions/15457547/java-math-pow-method?rq=1 –

+0

得到一些見解是的,我想知道調用Math.pow的語法。 David發佈的鏈接似乎是我需要看到的,謝謝。下次我會盡量不要這麼冗長。 –

回答

2

的公式可以轉換爲Java作爲:

double duration = numberOfYears * 12 
double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), duration) 
+0

This是一個非常具體的答案;非常感謝你! –

+0

+1爲好的答案。非常小的一點 - 我會用'numberOfMonths'這個名稱來代替'duration',只是爲了讓它更清晰。 –

2
// if you want e^b: 
double result = Math.exp(b); 

// if you want a^b: 
double result = Math.pow(a, b); 

而且不要忘了:

import java.lang.Math; 
0

這是如何使用Math.pow()

Math.pow (x,y); // x^y

其中x =(1 + monthlyInterestRate) 和y = numberOfYears * 12