C# 我的平方根c程序仅在判别式为0或小于0时有效,但在大于0时无效
试试这个:C# 我的平方根c程序仅在判别式为0或小于0时有效,但在大于0时无效,c#,string,parsing,if-statement,square-root,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);
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));
}
}
您将公式括起来不正确。平方根,而不是平方根。另外,您不应该取判别式的平方根吗?不是吗?Math.Sqrtdiscriminant解决了这个问题,不是吗?括号中有错误,根是-coefficientB+Math.Sqrtdiscriminant/2*coefficientA和-coefficientB-Math.Sqrtdiscriminant/2*coefficientA。即使在编辑之后,'root1=-coefficientB+discriminant/2*coefficientA;'还有,请注意“root2”缺少“-b”。@MartinJames-是的,我注意到了,但他没有使用root1或root2,所以我决定忽略它。@MartinJames-Ta。我修好了-b。
txtOutput.Text = "Equation has two real roots: " +
"\r\nroot1: " +
(-coefficientB + Math.Sqrt(discriminant)) / (2 * coefficientA) +
"\r\nroot2: " +
(-coefficientB - Math.Sqrt(discriminant)) / (2 * coefficientA);