解一元二次方程ax2+bx+c=0(C#代碼)
/// <summary>
/// 解一元二次方程ax2+bx+c=0
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="solution">解數組</param>
/// <returns>返回解的個數</returns>
public static int solution2equation(double a,double b,double c, double[] solution)
{
double delt = b * b - 4 * a * c;
if (delt >= 0)
{
if (a > 1e-10)
{
solution[0] = (-b + System.Math.Sqrt(delt)) / (2 * a);
solution[1] = (-b - System.Math.Sqrt(delt)) / (2 * a);
}
else
{
solution[0] = (2 * c)/(-b + System.Math.Sqrt(delt)) ;
solution[1] = (2 * c)/(-b - System.Math.Sqrt(delt)) ;
}
return 2;
}
else
{
return 0;
}
}
public static int solution2equation(double[] coefficient, double[] solution)
{
double a = coefficient[0];
double b = coefficient[1];
double c = coefficient[2];
return solution2equation(a, b, c, solution);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.