你能告诉我解决二次方程的代码有什么问题吗? 不要被我的工作弄掉,因为我对这个项目还很陌生。
class Program
{
static void Main(string[] args)
{
double a, b, c, x1, x2, x, D;
String A;
String B;
String C;
Console.Write("a=");
A = Console.ReadLine();
Console.Write("b=");
B = Console.ReadLine();
Console.Write("c=");
C = Console.ReadLine();
a = Convert.ToDouble(A);
b = Convert.ToDouble(B);
c = Convert.ToDouble(C);
D =(b * b - 4 * a * c);
if (D > 0)
{
x1 = (-b + Math.Sqrt(D)) / (2 * a);
x2 = (-b - Math.Sqrt(D)) / (2 * a);
Console.WriteLine("x1=" + x1);
Console.WriteLine("x2=" + x2);
}
else
if (D < 0)
{
D = -D;
x1 = (-b + Math.Sqrt(D)) / (2 * a);
x2 = (-b - Math.Sqrt(D)) / (2 * a);
}
else
{
x = (-b / (2 * a));
Console.WriteLine("x=" + x);
}
Console.ReadKey();
}
}
运行时不会显示任何值。
答案 0 :(得分:1)
尝试类似
的内容class Program
{
static void Main(string[] args)
{
double a, b, c, x1, x2, x, D;
String A;
String B;
String C;
Console.Write("a=");
A = Console.ReadLine();
Console.Write("b=");
B = Console.ReadLine();
Console.Write("c=");
C = Console.ReadLine();
a = Convert.ToDouble(A);
b = Convert.ToDouble(B);
c = Convert.ToDouble(C);
if (a != 0)
{
D = (b * b - 4 * a * c);
if (D > 0)
{
x1 = (-b + Math.Sqrt(D)) / (2 * a);
x2 = (-b - Math.Sqrt(D)) / (2 * a);
Console.WriteLine("x1=" + x1);
Console.WriteLine("x2=" + x2);
}
else
{
if (D < 0)
{
D = -D;
//x1 = (-b + Math.Sqrt(D)) / (2 * a);
//x2 = (-b - Math.Sqrt(D)) / (2 * a);
string complexX1 = ((-b) / (2 * a)).ToString() + "+" + (Math.Sqrt(D) / 2 * a).ToString() + "i";
string complexX2 = ((-b) / (2 * a)).ToString() + "-" + (Math.Sqrt(D) / 2 * a).ToString() + "i";
Console.WriteLine("complex x1=" + complexX1);
Console.WriteLine("complex x2=" + complexX2);
}
else
{
x = (-b / (2 * a));
Console.WriteLine("x=" + x);
}
}
}
else
{
if (b != 0)
{
x = -c / b;
Console.WriteLine("Grade 1 equation");
Console.WriteLine("x=" + x);
}
else
{
Console.WriteLine("No equation.");
}
}
Console.ReadKey();
}
}
在所有情况下,您似乎都没有写入控制台。
而且复杂根的处理方式也不完全正确,因为“i”缺失,因此数字的实部和虚部都缺失了。现在结果对于复杂的根也应该没问题。
我更新了代码所以现在也是当a为0(方程式不是二次方程式)且b为0(没有方程式)的情况下。
答案 1 :(得分:1)
不要将所有内容都塞进一个Main
方法中,分解您的实现!
在你的情况下,让我们提取一个方法:
// IEnumerable<Double>: quadratic equation can have 0..2 distinct real roots
private static IEnumerable<Double> SolveQuadratic(double a, double b, double c) {
double D = b * b - 4 * a * c;
if (D < 0)
yield break; // No real solutions (they are both complex ones)
else if (D == 0)
yield return -b / (2 * a); // One distinct root
else {
// Two distinct solutions
yield return (-b - Math.Sqrt(D)) / (2 * a);
yield return (-b + Math.Sqrt(D)) / (2 * a);
}
}
然后使用它:
...
a = Convert.ToDouble(A);
b = Convert.ToDouble(B);
c = Convert.ToDouble(C);
var result = SolveQuadratic(a, b, c)
.Select((x, i) => $"x{i + 1} = {x}");
Console.Write(String.Join(Environment.NewLine, result));
Console.ReadKey();