4. 解一元二次方程式

namespace Q4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double a = double.Parse(textBox1.Text);
            double b = double.Parse(textBox2.Text);
            double c = double.Parse(textBox3.Text);

            label4.Text = $"({a})x2+({b})x+({c})";

            double d = b * b - 4 * a * c;

            if (a == 0 && b == 0)
            {
                if (c == 0)
                {
                    textBox4.Text = "無限多解";
                }
                else
                    textBox4.Text = "無解";
                return;
            }

            if (a == 0 && b != 0)
            {
                textBox5.Text = "只有一解";
                textBox4.Text = $"{f2(-c / b)}";
                return;
            }

            if (a != 0 && b != 0 && d == 0)
            {
                textBox4.Text = $"{f2(-b / (2 * a))}";
                textBox5.Text = "同根";
            }

            if (a != 0 && b != 0 && d > 0)
            {
                double x1 = (-b + Math.Sqrt(d)) / (2 * a);
                double x2 = (-b - Math.Sqrt(d)) / (2 * a);

                if (x1 == x2)
                {
                    textBox4.Text = $"{f2(x1)}";
                    textBox5.Text = "同根";
                }
                else
                {
                    textBox4.Text = $"{f2(x1)}";
                    textBox5.Text = $"{f2(x2)}";
                }
                return;
            }

            if (a != 0 && b != 0 && d < 0)
            {
                double x1 = -b / (2 * a);
                double x1i = Math.Sqrt(4 * a * c - b * b) / (2 * a);

                textBox4.Text = $"{f2(x1)}+{f2(x1i)}i";
                textBox5.Text = $"{f2(x1)}-{f2(x1i)}i";
            }
        }


        string f2(double d)
        {
            return (Math.Round(d * 100) / 100).ToString();
        }
    }
}

Last updated