Haskell程式:計算單利和複利
在本教程中,我們將討論編寫一個使用Haskell程式語言計算單利和複利的程式。
在本教程中,我們將看到
計算單利的程式。
計算複利的程式。
單利是一種投資利息計算方法,其公式為I = p*t*r/100,
其中p為投資金額,t為時間(年),r為利率(百分比)。
例如 - 對於投資金額1000(p),t=2,r=3,利息為60。
複利是一種投資利息計算方法,其公式為I = p(1+r/n)^nt - p,
其中p為投資金額,t為時間(年),r為利率(百分比),n為每年複利次數。
例如 - 對於投資金額1000(p),t=1,n=1,r=3,本利和為1030。
演算法步驟
宣告或輸入金額及所有引數。
實現計算單利和複利的程式。
列印或顯示單利和複利。
示例1
計算單利的程式。
-- function declaration for function simpleInterest simpleInterest :: Float->Float->Float->Float -- function definition for function simpleInterest simpleInterest p t r = (p*t*r)/100 main = do -- declaring and initializing variables for interest parameters let p = 1000 let t = 2 let r = 3 -- invoking the function simpleInterest and loading into a variable interest let interest = simpleInterest p t r -- printing the interest print("Principle Amount, Time and Rate of Interest are =") print(p,t,r) print ("The Simple interest is:") print (interest)
輸出
"Principle Amount, Time and Rate of Interest are =" (1000.0,2.0,3.0) "The Simple interest is:" 60.0
在上面的程式中,我們聲明瞭一個函式simpleInterest,它接受三個浮點數作為引數並返回一個浮點數。在函式定義中,我們取三個變數p、t和r作為引數。我們使用適當的計算邏輯計算單利並返回計算值。在主函式中,我們宣告並初始化了本金(p)、時間(t)和利率(r)的三個變數。最後,我們用引數p、t和r呼叫函式simpleInterest,將返回值載入到變數interest中,並列印利息。
示例2
計算複利的程式。
-- function declaration for function compoundInterest compoundInterest :: Float->Float->Float->Float->Float -- function definition for function compoundInterest compoundInterest p t r n = p*((1 + r/(100*n))**(n*t)) - p main = do -- declaring and initializing variables for interest parameters let p = 1000 let t = 2 let r = 3 let n = 1 -- invoking the function simpleInterest and loading into a variable interest let interest = compoundInterest p t r n -- printing the interest print("Principle Amount, Time and Rate of Interest are =") print(p,t,r) print ("The Compound interest is:") print (interest)
輸出
"Principle Amount, Time and Rate of Interest are =" (1000.0,2.0,3.0) "The Compound interest is:" 60.900024
在上面的程式中,我們聲明瞭一個函式compoundInterest,它接受四個浮點數作為引數並返回一個浮點數。在函式定義中,我們取四個變數p、t、n和r作為引數。我們使用適當的計算邏輯計算複利並返回計算值。在主函式中,我們宣告並初始化了本金(p)、時間(t)、每年複利次數(n)和利率(r)的四個變數。最後,我們用引數p、t、n和r呼叫函式compoundInterest,將返回值載入到變數interest中,並列印利息。
結論
在本教程中,我們討論了在Haskell程式語言中實現計算單利和複利程式的方法。