use std::fmt; #[derive(Debug)] pub struct MortgageState { period: u32, capital: f64, i12: f64, quota: f64, quotas: u32, } impl fmt::Display for MortgageState { 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 ) } } pub fn quota(capital: f64, i12: f64, quotas: u32) -> f64 { capital * i12 / (1.0 - (1.0 + i12).powi(-(quotas as i32))) } impl MortgageState { fn new(capital: f64, i1: f64, years: u32) -> Self { let quotas = years * 12; let i12 = i1 / 12.0; MortgageState { period: 0, capital, i12, quota: quota(capital, i12, quotas), quotas, } } pub fn step(&mut self) { self.period += 1; self.quotas -= 1; self.capital = (1.0 + self.i12) * self.capital - self.quota; } pub fn interests(&self) -> f64 { self.i12 * self.capital } pub fn amortized(&self) -> f64 { self.quota - self.interests() } } pub fn run_mortgage(capital: f64, i12: f64, years: u32) { let mut state = MortgageState::new(capital, i12, years); println!("Total a pagar: {}\n\n", state.quota * state.quotas as f64); println!("Cuota | c\tIn\tAn\tCn"); while state.quotas > 0 { println!("{state}"); state.step(); } }