题解 | #计算一元二次方程#
计算一元二次方程
https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
public class Program { public static void Main() { string line; while ((line = System.Console.ReadLine()) != null) { string[] lines = line.Split(" "); double a = double.Parse(lines[0]); double b = double.Parse(lines[1]); double c = double.Parse(lines[2]); if (a != 0) { //计算△ double delta = (b * b) - (4 * a * c); //△=0,两个实根相等 if (delta == 0) { //-b+-0/(2*a) double x = -b / (2.0 * a); System.Console.WriteLine("x1=x2={0}", x.ToString("F2")); } //△>0,两个实根不等,根据求根公式x=(-b正负根号b平方-4ac)/2a去计算 else if (delta > 0) { double x1 = (-b - System.Math.Sqrt(delta)) / (2.0 * a); double x2 = (-b + System.Math.Sqrt(delta)) / (2.0 * a); System.Console.WriteLine("x1={0};x2={1}", x1.ToString("F2"), x2.ToString("F2")); } //△<0,有两个虚根 else if (delta < 0) { //计算实部 double x1 = -b / (2.0 * a); //计算虚部 double x2 = System.Math.Sqrt(-delta) / (2.0 * a); System.Console.WriteLine("x1={0}-{1}i;x2={2}+{3}i", x1.ToString("F2"), x2.ToString("F2"), x1.ToString("F2"), x2.ToString("F2")); } } else if (a == 0) System.Console.WriteLine("Not quadratic equation"); } } }