Swift程式計算簡單利息和複利
本教程將討論如何編寫一個Swift程式來計算簡單利息和複利。
複利
在一定時期內,對本金和利息一起產生的利息稱為複利。或者換句話說,複利被稱為利息上的利息。它是在計算本金和利息之後計算的。
公式
以下是複利公式:
Amount(A) = Principal(P)(1 + Rate/100)Time(t)
C.I = Amount(A) - Principal(P)
其中
本金(P) - 本金代表最初投資的金額。
利率(R) - 利率代表在給定時間段內應用於本金的利率。
時間(T) - 時間代表投資金額的時間段。
金額(A) - 金額代表包括本金和利息金額在內的總返還金額。
簡單利息
簡單利息是用於在給定時間段內查詢資金利息的最常用方法。在這種方法中,利息始終以相同的利率應用於原始本金,並在每個時間段內保持不變。它是透過將利率乘以本金和時間來計算的。
公式
以下是簡單利息公式:
S.I = Principal Amount(P) x Time(T) x Rate(R)/100
其中
本金(P) - 本金代表最初投資的金額。
利率(R) - 利率代表在給定時間段內應用於本金的利率。
時間(T) - 時間代表投資金額的時間段。
計算簡單利息和複利的演算法
步驟1 - 定義3個變數:本金、利率和期限
步驟2 - 為這三個變數賦值
步驟3 - 定義簡單利息和複利的函式
步驟4 - 將值透過簡單利息和複利函式執行
步驟5 - 在輸出螢幕上顯示最終結果
示例1
以下程式展示瞭如何計算簡單利息和複利。
import Foundation import Glibc func simpleInterest(Principal: Double, Rate: Double, Time: Double) -> Double{ let Result1 = Principal * Time * Rate / 100 return Result1 } func compoundInterest(Principal: Double, Rate: Double, Time: Double) -> Double{ let amount = Principal * pow((1 + Rate/100), Time) let Result2 = amount - Principal return Result2 } print("Simple Interest is - ", simpleInterest(Principal:10000, Rate: 5, Time:5)) print("Compound Interest is - ", compoundInterest(Principal:10000, Rate: 5, Time:5))
輸出
Simple Interest is - 2500.0 Compound Interest is - 2762.815625000003
在上面的程式碼中,我們建立了兩個名為simpleInterest()和compoundInterest()的函式。simpleInterest()函式使用數學公式返回給定資料(即本金、利率、時間)的簡單利息,而compoundInterest()函式使用數學公式返回給定資料(即本金、利率、時間)的複利。現在,透過呼叫simpleInterest()和compoundInterest()函式以及三個引數的值(本金:10000、利率:5、時間:5)來顯示簡單利息和複利。
本金:10000,利率:5,時間:5
示例2
以下程式展示瞭如何透過獲取使用者輸入來計算簡單利息和複利。
import Foundation import Glibc print("Please enter principal-") var Principal = Double(readLine()!)! print(Principal) print("Please enter rate-") var Rate = Double(readLine()!)! print(Rate) print("Please enter time duration-") var Duration = Double(readLine()!)! print(Duration) func simpleInterest(P: Double, R: Double, T: Double) -> Double{ let Result1 = P * T * R / 100 return Result1 } func compoundInterest(P: Double, R: Double, T: Double) -> Double{ let A = P * pow((1 + R/100), T) let Result2 = A - P return Result2 } print("Press 1 for simple interest\n Press 2 for Compound Interest") var choice = Int(readLine()!)! switch choice{ case 1: print("Simple Interest is - ", simpleInterest(P: Principal, R: Rate, T: Duration)) case 2: print("Compound Interest is - ", compoundInterest(P: Principal, R: Rate, T: Duration)) default: print("Not a valid choice") }
標準輸入
Please enter principal- 10000 Please enter rate- 3 Please enter time duration- 6 Press 1 for simple interest Press 2 for Compound Interest 2
輸出
Compound Interest is - 1940.5229652900016
在上面的程式碼中,我們首先從使用者那裡獲取本金、利率和時間的值。之後,我們建立了兩個名為simpleInterest()和compoundInterest()的函式。顧名思義,simpleInterest()函式返回簡單利息,compoundInterest()函式返回輸入值的複利。現在,我們詢問使用者如果他們想要複利,則按1,如果他們想要簡單利息,則按2。這裡使用者按2,因此程式的控制權進入switch case語句並顯示覆利,即1940.5229652900016。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP