2026-04-27 16:48:37 -06:00
|
|
|
pub struct Fraction {
|
|
|
|
|
num: i64,
|
|
|
|
|
den: i64,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub enum FractionError {
|
|
|
|
|
DivisionByZero,
|
|
|
|
|
ZeroDenominator,
|
|
|
|
|
Overflow,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Display for FractionError {
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
|
match self {
|
|
|
|
|
FractionError::DivisionByZero => write!(f, "Division by zero"),
|
|
|
|
|
FractionError::ZeroDenominator => write!(f, "Denominator can't be zero"),
|
|
|
|
|
FractionError::Overflow => write!(f, "Numeric overflow"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::error::Error for FractionError {}
|
|
|
|
|
|
|
|
|
|
impl Fraction {
|
|
|
|
|
pub fn new(num: i64, den: i64) -> Result<Self, FractionError> {
|
|
|
|
|
if den == 0 {
|
|
|
|
|
return Err(FractionError::ZeroDenominator);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(Fraction { num, den })
|
|
|
|
|
}
|
2026-04-27 16:37:18 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests {
|
|
|
|
|
use super::*;
|
|
|
|
|
}
|