use std::f64; // For floating-point operations
fn calculate_compound_interest(principal: f64, rate: f64, years: f64) -> f64 {
// Validate input: all values must be non-negative
if principal < 0.0 || rate < 0.0 || years < 0.0 {
eprintln!("Error: Principal, rate, and years must be non-negative values.");
return -1.0;
}
// Calculate total amount using the compound interest formula
let amount = principal * (1.0 + rate / 100.0).powf(years);
// Return compound interest (total amount - principal)
amount - principal
}
fn main() {
let principal = 100_000.0;
let rate = 3.5;
let years = 5.0;
let compound_interest = calculate_compound_interest(principal, rate, years);
if compound_interest >= 0.0 {
println!("Principal Amount: {:.2}", principal);
println!("Annual Interest Rate: {:.2}%", rate);
println!("Years: {:.2}", years);
println!("Compound Interest: {:.2}", compound_interest);
println!("Total Amount: {:.2}", principal + compound_interest);
}
}
/*
run:
Principal Amount: 100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: 18768.63
Total Amount: 118768.63
*/