平方根的c#程序仅在判别式为0或小于0时​​有效,但在大于0时则不起作用

时间:2015-02-16 00:52:37

标签: c# string parsing if-statement square-root

private void btnCompute_Click(object sender, EventArgs e)
{
    double coefficientA;
    double coefficientB;
    double coefficientC;
    double root1;
    double root2;
    double discriminant;

    coefficientA = double.Parse(txtCoeA.Text);
    coefficientB = double.Parse(txtCoeB.Text);
    coefficientC = double.Parse(txtCoeC.Text);

    discriminant = 
            (coefficientB * coefficientB) - 
            (4 * coefficientA * coefficientC);

    txtOutput.Text = "Discriminant = " + discriminant.ToString("N2");

    //-b/2a

    root1 = (-coefficientB + discriminant) / (2 * coefficientA);
    root2 = (-coefficientB - discriminant) / (2 * coefficientA);

    if (discriminant < 0)
    {
            txtOutput.Text += "\r\nEquation has no real roots!";
    }
    else if (discriminant == 0)
    {
        txtOutput.Text += 
            "\r\nEquation has one root: " + root2.ToString("N2");
    }        
    else if (discriminant > 0)
    {
        txtOutput.Text = "Equation has two real roots: " +
            "\r\nroot1: " + 
            (-coefficientB + Math.Sqrt(discriminant) / 
            (2 * coefficientA)) +
            "\r\nroot2: " + (coefficientB - Math.Sqrt(discriminant) / 
            (2 * coefficientA)); 
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

    txtOutput.Text = "Equation has two real roots: " +
        "\r\nroot1: " + 
        (-coefficientB + Math.Sqrt(discriminant)) / (2 * coefficientA) +
        "\r\nroot2: " +
        (-coefficientB - Math.Sqrt(discriminant)) / (2 * coefficientA);

您错误地包含了公式。