2017-04-15 90 views
1

所以我在C#中編寫了一個二次公式程序,我如何取二次公式程序並對其進行修改,以便程序正確顯示解決方案的數量。如何顯示二次公式的解決方案

如果有兩個解決方案,

(x - x1)(x - x2) = 0 

如果只有一個解決方案,

(x - x0)^2 = 0 

如果沒有解決方案,

無解。

這是一個程序,如果有人能爲我展示這個解決方案對我來說將是美好的,我真的被困在如何去做。

using System; 

namespace quadraticequation 
{ 
class MainClass 
{ 
    public static void Main(string[] args) 
    { 
     Console.WriteLine("Enter a number for a"); //ask the user for information 
     double a = double.Parse(Console.ReadLine()); //Gets a from the user 
     Console.WriteLine("Enter a number for b"); //asks the user for information 
     double b = double.Parse(Console.ReadLine()); //Gets b from the user 
     Console.WriteLine("Enter a number for c"); //asks the user for information 
     double c = double.Parse(Console.ReadLine()); //Gets c from the user 

     //double.Parse --> is used to convert a number or string to a double. 
     //Console.ReadLine() --> is used to take the input from the user. 

     //We call a function here 
     Quadratic(a, b, c); 

    } 
    //We need to create a new function 

    public static void Quadratic(double a, double b, double c) 
    { 
     double deltaRoot = Math.Sqrt(b * b - 4 * a * c); //Math.Sqrt takes the square root of the number 


     if (deltaRoot >= 0) // we use an if statement here to handle information 
     { 
      double x1 = (-b + deltaRoot)/2 * a; //We write the information for x1 here 
      double x2 = (-b - deltaRoot)/2 * a; //We write the information for x2 here 
      Console.WriteLine("x1 = " + x1 + " x2 = " + x2); //we use this to write the roots 



     } 
     else // we use an else statement so that we dont return an error when there are no roots 
     { 
      Console.WriteLine("There are no roots"); 

     } 



    } 
} 
} 
+2

我是正確的假設,只希望*實時*解決方案,而不是複雜的? –

回答

3

我認爲你必須檢查你的秒度公式解 -skills。你寫:

double deltaRoot = Math.Sqrt(b * b - 4 * a * c);

但測試實際上是是否b -4 ×一個×ç大於或等於零:的確,其實就是爲什麼我們檢查一下:因爲我們不能拿負數的平方根(是的,存在複數數字可以採取負數的平方根,但我們暫時忽略)。

所以解決的辦法就是把它寫這樣的:

public static void Quadratic(double a, double b, double c) { 
    double delta = b*b-4*a*c; //only delta 

    if (delta > 0) { 
     double deltaRoot = Math.Sqrt(delta); 
     double x1 = (-b + deltaRoot)/(2 * a); //We write the information for x1 here 
     double x2 = (-b - deltaRoot)/(2 * a); //We write the information for x2 here 
     Console.WriteLine("x1 = " + x1 + " x2 = " + x2); //we use this to write the roots 
    } else if(delta == 0) { 
     double x1 = -b/(2*a); 
     Console.WriteLine("x1 = " + x1); //we use this to write the roots 
    } else { 
     Console.WriteLine("There are no roots"); 
    } 

}

你還必須寫(-b + deltaRoot)/(2*a)(與(2*a)),否則就會(-b + deltaRoot)/2a乘法來代替。

最後要說明的是,與浮點的等式比較非常棘手,所以delta == 0通常會失敗,因爲結果可能是1e-20 -ish,這只是執行浮點算法時的錯誤。因此,使用小範圍的值可能會更好。

這給:

csharp> MainClass.Quadratic(1,1,1); 
There are no roots 
csharp> MainClass.Quadratic(1,1,0); 
x1 = 0 x2 = -1 
csharp> MainClass.Quadratic(1,0,0); 
x1 = 0 
+0

非常感謝你解釋這一點。 –