窗体上放置三个TextBox,分别输入a,b,c的值,控件命名:tbA,tbB,tbC
再放一个Button,设置Text为:求解,其单击后台代码如下:
private void button1_Click(object sender, EventArgs e)
{
double a = 0;
double b = 0;
double c = 0;
try
{
if (tbA.Text.Length == 0)
{
MessageBox.Show("请输入a的值", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
a = Convert.ToDouble(tbA.Text);
}
catch
{
MessageBox.Show("您输入的a的值不是一个数字,请重新输入", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
tbA.Focus();
return;
}
try
{
if (tbB.Text.Length == 0)
{
MessageBox.Show("请输入b的值", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
b = Convert.ToDouble(tbB.Text);
}
catch
{
MessageBox.Show("您输入的b的值不是一个数字,请重新输入", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
tbB.Focus();
return;
}
try
{
if (tbC.Text.Length == 0)
{
MessageBox.Show("请输入c的值", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
c = Convert.ToDouble(tbC.Text);
}
catch
{
MessageBox.Show("您输入的c的值不是一个数字,请重新输入", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
tbC.Focus();
return;
}
if (a == 0)
{
if (b == 0)
{
if (c == 0)
{
MessageBox.Show(string.Format("方程{0}x^2+{1}x+{2}=0的解为 x={3}", a, b, c, "任意实数"), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(string.Format("方程{0}x^2+{1}x+{2}=0无实数解", a, b, c), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show(string.Format("方程{0}x^2+{1}x+{2}=0的解为 x={3}", a, b, c, -c / b), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
double delta = b * b - 4 * a * c;
if (delta < 0)
{
MessageBox.Show(string.Format("方程{0}x^2+{1}x+{2}=0无实数解", a, b, c), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(string.Format("方程{0}x^2+{1}x+{2}=0的解为 x1={3} , x2={4}", a, b, c, (-b + System.Math.Sqrt(delta)) / 2 / a, (-b - System.Math.Sqrt(delta)) / 2 / a), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}