2014-02-26 28 views
0

我的程序有一行根據使用Math.pow方法的公式計算複合關聯。當變量類型爲int時,Math.pow不起作用

當變量loanRate在該程序的原始版本中被聲明爲Integer時,該公式根本不起作用,只會返回0;

我將loanRate更改爲Double,如下所示,因爲某些原因,程序正在運行。

很抱歉,如果這是一個非常簡單的問題,我只是不知道爲什麼Math.pow方法不會與我Int工作,如果後面有使用Math.pow的一般原則,即時通訊失蹤?

在此先感謝您的幫助。

// Variables & Constants 
int principle, i; 
double simpleInt, compoundInt, difference, loanRate; 

// Prompts user to enter principle and rate 
System.out.print("Enter Principle: "); // keep print line open 
principle = console.nextInt(); 
System.out.println(); 

System.out.print("Enter Rate: "); 
loanRate = console.nextDouble(); 

// Header 


// Caculates and Outputs Simple, Compound and Difference for the loan 
// in 5 year intervals from 5 to 30 

for (i = 5; i <= 30; i = i + 5) 
{ 
    simpleInt = principle * loanRate/100 * i; 
    compoundInt = principle * ((Math.pow((1 + loanRate/100),i))-1); 
    difference = compoundInt - simpleInt; 


    System.out.printf("\n %7d %7.2f %7.2f %7.2f", i, simpleInt, compoundInt, difference); 
} 
+5

這只是因爲你正在進行整數除法。 –

回答

1

compoundInt = principle * ((Math.pow((1 + loanRate/100),i))-1);

loanRate/100這裏是關鍵,因爲loadRate是< 100比這樣的等分結果將是0更改爲loanRate/100.0,這將解決這個問題。

+0

非常感謝! :) –

相關問題