c#中的二次方程求解器

本文关键字:二次方程 | 更新日期: 2023-09-27 18:17:24

我试着用c#写一个简单的二次方程求解器,但由于某种原因,它并没有给我正确的答案。事实上,它给我的答案是非常大的数字,通常是数百万。

有谁能给点光吗?我得到的正根和负根的答案是一样的。(尝试了两种不同的数学方法)

static void Main(string[] args)
    {
        int a;
        int b;
        int c;
        Console.WriteLine("Hi, this is a Quadratic Equation Solver!");
        Console.WriteLine("a-value: ");
        try
        {
            a = int.Parse(Console.ReadLine());
            Console.WriteLine("b-value: ");
            b = int.Parse(Console.ReadLine());
            Console.WriteLine("c-value: ");
            c = int.Parse(Console.ReadLine());
            Console.WriteLine("Okay, so your positive root is: " + quadForm(a, b, c, true));
            Console.WriteLine("And your negative root is: " + quadForm(a, b, c, false));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        Console.ReadLine();
    }
    static int quadForm(int a, int b, int c, Boolean pos)
    {
        int x = 0;
        if (pos)
            x = ((-b + (int) (Math.Sqrt((b * b) - (4 * a * c)))) / (2 * a));
        else
            x = ((-Math.Abs(b) - (int) (Math.Sqrt(Math.Pow(b,2) - (4 * a * c)))) / (2 * a));
        return x;
    }

c#中的二次方程求解器

试试这个版本的quadForm:

static double quadForm(int a, int b, int c, bool pos)
{
    var preRoot = b * b - 4 * a * c;
    if (preRoot < 0)
    {
        return double.NaN;
    }
    else
    {
        var sgn = pos ? 1.0 : -1.0;
        return (sgn * Math.Sqrt(preRoot) - b) / (2.0 * a);
    }
}