import Foundation
func calculateCompoundInterest(principal: Double, rate: Double, years: Double) -> Double {
// Validate input: all values must be non-negative
guard principal >= 0, rate >= 0, years >= 0 else {
print("Error: Principal, rate, and years must be non-negative values.")
return -1
}
// Calculate total amount using the compound interest formula
let amount = principal * pow(1 + rate / 100, years)
// Return compound interest (total amount - principal)
return amount - principal
}
let principal: Double = 100_000
let rate: Double = 3.5
let years: Double = 5
let compoundInterest = calculateCompoundInterest(principal: principal, rate: rate, years: years)
if compoundInterest >= 0 {
print(String(format: "Principal Amount: $%.2f", principal))
print(String(format: "Annual Interest Rate: %.2f%%", rate))
print(String(format: "Years: %.2f", years))
print(String(format: "Compound Interest: $%.2f", compoundInterest))
print(String(format: "Total Amount: $%.2f", principal + compoundInterest))
}
/*
run:
Principal Amount: $100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: $18768.63
Total Amount: $118768.63
*/