改一下代码namespace ConsoleApp10 { internal class Program { static void Main(string[] args) { double a, b, c, delta, x1, x2, realPart, imagPart; Console.Write("请输入系数a:"); String s = Console.ReadLine(); a = double.Parse(s);//系数a Console.Write("请输入系数b:"); s = Console.ReadLine(); b = double.Parse(s);//系数b Console.Write("请输入系数c:"); s = Console.ReadLine(); c = double.Parse(s);//系数c if (a == 0) { if (b == 0) Console.WriteLine("此方程无解!"); else Console.WriteLine("此方程的解为:{0},-c/b"); } else { delta = b * b - 4 * a * c; if (delta > 0) ; { x1 = (-b + Math.Sqrt(delta)) / (2 * a); x2 = (-b - Math.Sqrt(delta)) / (2 * a); Console.WriteLine("此方程有两个不等实根:{0}和{1}", x1, x2); } else { if (delta == 0) ; else { realPart = -b / (2 * a); imagPart = Math.Sqrt(delta) / (2 * a); Console.WriteLine("此方程有两个共轭复根:{0}+{1}i和{0}-{1}i", realPart, imagPart); } } } Console.ReadKey(); } } }
时间: 2023-05-18 12:03:16 浏览: 93
以下是修改后的代码:
namespace ConsoleApp10
{
internal class Program
{
static void Main(string[] args)
{
double a, b, c, delta, x1, x2, realPart, imagPart;
Console.Write("请输入系数a:");
String s = Console.ReadLine();
a = double.Parse(s);//系数a
Console.Write("请输入系数b:");
s = Console.ReadLine();
b = double.Parse(s);//系数b
Console.Write("请输入系数c:");
s = Console.ReadLine();
c = double.Parse(s);//系数c
if (a == 0)
{
if (b == 0) Console.WriteLine("此方程无解!");
else Console.WriteLine("此方程的解为:{0}", -c / b);
}
else
{
delta = b * b - 4 * a * c;
if (delta > 0)
{
x1 = (-b + Math.Sqrt(delta)) / (2 * a);
x2 = (-b - Math.Sqrt(delta)) / (2 * a);
Console.WriteLine("此方程有两个不等实根:{0}和{1}", x1, x2);
}
else if (delta == 0)
{
x1 = -b / (2 * a);
Console.WriteLine("此方程有一个实根:{0}", x1);
}
else
{
realPart = -b / (2 * a);
imagPart = Math.Sqrt(-delta) / (2 * a);
Console.WriteLine("此方程有两个共轭复根:{0}+{1}i和{0}-{1}i", realPart, imagPart);
}
}
Console.ReadKey();
}
}
}
请注意,我对代码进行了一些修改,以修复一些错误。我添加了一个 else if 语句来处理 delta 等于 0 的情况,并且在计算虚部时使用了负数的平方根。
阅读全文