实现说明
除了函数 roots、main,文件里再无其他定义。
分支逻辑走 match,穷尽性检查把漏掉的分支变成编译错误。
使用要点
main按顺序串起roots;运行文件就会把这个流程跑一遍。
常见问题
「判别式 Ordering match 求根分类」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
入口签名:fn roots(a: f64, b: f64, c: f64) -> String
核心语句
Some(Ordering::Greater) => {
let d = discriminant.sqrt();
format!("two roots: {} and {}", (-b + d) / (2.0 * a), (-b - d) / (2.0 * a))
}
代码示例
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));
}