Quadratic Roots Discriminant Match Ordering

Match the discriminant's Ordering to report two roots, one repeated root, no real roots, or undefined for NaN input.

RustData Integrity

Code

rustsnippet
23 lines
use std::cmp::Ordering;

// quadratic: a*x^2 + b*x + c = 0, root count follows the discriminant
fn roots(a: f64, b: f64, c: f64) -> String {
    let discriminant = b * b - 4.0 * a * c;
    match discriminant.partial_cmp(&0.0) {
        Some(Ordering::Greater) => {
            let d = discriminant.sqrt();
            format!("two roots: {} and {}", (-b + d) / (2.0 * a), (-b - d) / (2.0 * a))
        }
        Some(Ordering::Equal) => format!("one root: {}", -b / (2.0 * a)),
        Some(Ordering::Less) => String::from("no real roots"),
        // NaN discriminant (bad input) compares to nothing and lands here
        None => String::from("undefined"),
    }
}

fn main() {
    println!("{}", roots(1.0, -3.0, 2.0));
    println!("{}", roots(1.0, -2.0, 1.0));
    println!("{}", roots(1.0, 0.0, 1.0));
    println!("{}", roots(0.0, f64::NAN, 1.0));
}

Inside this example — Quadratic Roots Discriminant Match Ordering

Quadratic Roots Discriminant Match Ordering keeps everything in the functions roots and main.

Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Points of care

  • No third-party surface — nothing external to audit before running.

Using it

The pivotal declaration: fn roots(a: f64, b: f64, c: f64) -> String

Execute the file and main walks through roots, in that order.

Key statements

Some(Ordering::Greater) => {
    let d = discriminant.sqrt();
    format!("two roots: {} and {}", (-b + d) / (2.0 * a), (-b - d) / (2.0 * a))
}

Interactive Tools for This Topic

FAQ

How do you run Quadratic Roots Discriminant Match Ordering?
Just run the file; everything it needs ships with the runtime itself.