【发布时间】:2010-11-08 22:45:26
【问题描述】:
我构建了一个极其简单但功能齐全且非常有用的 WinForms C# 应用程序,它可以求解二次方程的实根。
这是我目前的编程逻辑:
string noDivideByZero = "Enter an a value that isn't 0";
txtSolution1.Text = noDivideByZero;
txtSolution2.Text = noDivideByZero;
decimal aValue = nmcA.Value;
decimal bValue = nmcB.Value;
decimal cValue = nmcC.Value;
decimal solution1, solution2;
string solution1String, solution2String;
//Quadratic Formula: x = (-b +- sqrt(b^2 - 4ac)) / 2a
//Calculate discriminant
decimal insideSquareRoot = (bValue * bValue) - 4 * aValue * cValue;
if (insideSquareRoot < 0)
{
//No real solution
solution1String = "No real solutions!";
solution2String = "No real solutions!";
txtSolution1.Text = solution1String;
txtSolution2.Text = solution2String;
}
else if (insideSquareRoot == 0)
{
//One real solution
decimal sqrtOneSolution = (decimal)Math.Sqrt((double)insideSquareRoot);
solution1 = (-bValue + sqrtOneSolution) / (2 * aValue);
solution2String = "No real solution!";
txtSolution1.Text = solution1.ToString();
txtSolution2.Text = solution2String;
}
else if (insideSquareRoot > 0)
{
//Two real solutions
decimal sqrtTwoSolutions = (decimal)Math.Sqrt((double)insideSquareRoot);
solution1 = (-bValue + sqrtTwoSolutions) / (2 * aValue);
solution2 = (-bValue - sqrtTwoSolutions) / (2 * aValue);
txtSolution1.Text = solution1.ToString();
txtSolution2.Text = solution2.ToString();
}
txtSolution1和txtSolution2是文本框,不允许接收输入,但输出计算结果
nmcA、nmcB 和 nmcC 是 NumericUpDown 控件,用于最终用户输入的 a、b 和 c 值
好的,所以,我希望更进一步,并可能解决虚值。考虑到我已经设置了条件,只有当判别式等于 0 或小于 0 时,我才需要考虑虚值。
但是,我想不出解决此问题的好方法。当人们试图取负数的平方根时,就会出现复杂的解决方案,导致is 无处不在。 i = sqroot(-1) 和 i^2 = -1。
有谁知道如何解决这个问题,或者是否不值得花时间?
编辑
通过谷歌搜索,我发现 C# 4.0(或 .NET 4.0,我不确定是哪个)在 System.Numerics.Complex 中内置了复数支持。我现在正在检查。
【问题讨论】:
-
我不知道您为什么要将所有内容都转换为十进制,而且您无缘无故地取零的平方根(它始终为零并且对答案没有任何贡献),在这种情况下
solution2String应该是“重复的根”,而不是“没有真正的解决方案”。 -
哎呀,我忘了重复的根,它应该说
multiplicity of 0,或者类似的东西。感谢您指出了这一点!此外,十进制提供更高的准确性,不是吗? -
您在
double中进行数学运算,然后转换为decimal。所以不,你并没有获得更高的准确性,你只是在减慢工作速度。 -
我相信 .Net 4 框架只支持 CLR 4(因此是 C# 4)语言。见stackoverflow.com/questions/148833/…
-
@Ben,好的,我会解决这个问题并稍微更新代码。 @Peter 感谢您的参考。
标签: c# winforms polynomial-math complex-numbers quadratic