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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Quadratic Roots Discriminant Match Ordering?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.