我已經構建了一個非常簡單但功能完備並且相當有用的WinForms C#應用程序,它可以解決二次方程的實根。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
是用於由最終用戶輸入的a,b和c值的NumericUpDown控件
好的,所以我希望能夠採取一步進一步,並可能解決假想的價值。考慮到我已經建立了條件,只有當判別等於0
或小於0
時,我才需要考慮虛數值。
但是,我想不出一個好辦法來解決這個問題。當一個人試圖取一個負數的平方根時,就會出現複雜的解,導致出現在任何地方。 i = sqroot(-1)
和i^2 = -1
。
有誰知道如何解決這個問題,或者如果它只是不值得的時間?
編輯
隨着多一點谷歌搜索,我發現有可能與C#4.0(或.NET 4.0,我不知道哪)有內置的複數支持System.Numerics.Complex
。我現在正在檢查這個。
我不知道你爲什麼將所有內容都轉換爲十進制數,並且你沒有明顯的原因取得零的平方根(它總是零並且對答案沒有任何貢獻),在這種情況下,'solution2String'應該是「重複根」,而不是「沒有真正的解」。 – 2010-11-08 23:04:03
哎呀,我忘了重複的根,它應該說'多重性0',而不是,或類似的東西。感謝您指出了這一點!另外,十進制給出更高的準確性,不是嗎? – Qcom 2010-11-08 23:05:57
你正在做'double'的數學,然後轉換成'decimal'。所以不,你沒有得到更高的準確性,你只是放慢了工作。 – 2010-11-08 23:19:01