use std::fmt; #[derive(Debug)] pub struct Mortgage { period: u32, capital: f64, i12: f64, quota: f64, quotas: u32, } impl fmt::Display for Mortgage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{:5} | {:4.2}\t{:.2}\t{:.2}\t{:.2}", self.period, self.quota, self.interests(), self.amortized(), self.capital ) } } impl Mortgage { pub fn new(capital: f64, i1: f64, years: u32) -> Self { let quotas = years * 12; let i12 = i1 / 12.0; Mortgage { period: 0, capital, i12, quota: Self::quota(capital, i12, quotas), quotas, } } pub fn run(&mut self) { let to_pay = self.quota * self.quotas as f64; let capital = self.capital; let interest = to_pay - capital; println!("Cuota | c\tIn\tAn\tCn"); while self.quotas > 0 { println!("{self}"); self.step(); } println!( "\n== Total a pagar: {:.2} ({} cap + {interest:.2} int)", to_pay, capital ); println!( "== Los intereses suponen un {:.2}% del capital", 100. * interest / capital ); println!("\n"); } fn quota(capital: f64, i12: f64, quotas: u32) -> f64 { capital * i12 / (1.0 - (1.0 + i12).powi(-(quotas as i32))) } fn step(&mut self) { self.period += 1; self.quotas -= 1; self.capital = (1.0 + self.i12) * self.capital - self.quota; } fn interests(&self) -> f64 { self.i12 * self.capital } fn amortized(&self) -> f64 { self.quota - self.interests() } }