题解 | #计算一元二次方程#
计算一元二次方程
https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
use std::io::{self, *}; fn main() { let stdin = io::stdin(); for line in stdin.lock().lines() { let ll = line.unwrap(); let numbers: Vec<&str> = ll.split(" ").collect(); if numbers.len() != 3 { println!("请输入二元一次方程组的三个参数!"); continue; } let a = numbers[0].trim().parse::<f64>().unwrap_or(0.0); let b = numbers[1].trim().parse::<f64>().unwrap_or(0.0); let c = numbers[2].trim().parse::<f64>().unwrap_or(0.0); cal_quadratic_equation(a, b, c); } } /// # 功能 /// 计算一元二次方程组并打印结果 /// # 参数 /// * `a` - 平方项系数 /// * `b` - 一次方项系数 /// * `c` - 常数项 /// # 示例 /// 解二元一次方程 2x^2 + 7x + 1 = 0, /// 预期结果为`x1=-3.35;x2=-0.15` /// ``` /// cal_quadratic_equation(2.0, 7.0, 1.0); /// ``` /// # 备注 /// * 打印精度为小数点后两位 /// * 当方程没有实数解时会打印虚数解(实部+虚部) fn cal_quadratic_equation(a: f64, b: f64, c: f64) { let delta: f64 = b * b - 4.0 * a * c; //判别式 if a == 0.0 { println!("Not quadratic equation"); } else { if delta == 0.0 { println!("x1=x2={:.2}", -b / (2.0 * a)); } else if delta > 0.0 { println!( "x1={:.2};x2={:.2}", (-b - delta.sqrt()) / (2.0 * a), (-b + delta.sqrt()) / (2.0 * a) ); } else if delta < 0.0 { let real_quantity = -b / (2.0 * a); //实部 let imaginary_quantity = (-delta).sqrt() / (2.0 * a); //虚部 println!( "x1={:.2}-{:.2}i;x2={:.2}+{:.2}i", real_quantity, imaginary_quantity, real_quantity, imaginary_quantity ); } } }