This is a program I wrote to solve quadratic equations. I have three textboxes for inputting the value of a,b and c. If I use the following code, without assigning any value to a,b or c before the if statement, I get an error "Use of unassigned variable" in the line double Delta = Math.Pow(b, 2) - 4 * a * c;
, only regarding variable b and c(not a).
private void bt_Calculate_MouseClick(object sender, MouseEventArgs e)
{
Double a, b, c;
if (txt_b.Text != "" && txt_b.Text != "" && txt_c.Text != ""
&& (Double.TryParse(txt_a.Text, out a) && Double.TryParse(txt_b.Text, out b) && Double.TryParse(txt_c.Text, out c)) == true)
{
double Delta = Math.Pow(b, 2) - 4 * a * c;
if (Delta > 0)
{
Double x1 = Math.Round((-b + Math.Sqrt(Delta)) / (2 * a), 4);
Double x2 = Math.Round((-b - Math.Sqrt(Delta)) / (2 * a), 4);
txt_Result1.Text = Convert.ToString(x1);
txt_Result2.Text = Convert.ToString(x2);
}
else if (Delta == 0)
{
Double x1 = Math.Round(-b / (2 * a), 4);
txt_Result1.Text = Convert.ToString(x1);
}
else
{
MessageBox.Show("Impossible Equation.");
}
}
else if ((txt_a.Text == "") || (txt_b.Text == "") || (txt_c.Text == ""))
{
MessageBox.Show("Provide a value for a, b and c.");
}
else
{
MessageBox.Show("Provide a valid number, please");
}
}
However, the program doesn't give any error and outputs the right result when I assign the value 0 to all three variables before the if statement.
As such: Double a=0, b=0, c=0;
I would like to know why this happens exactly. Isn't TryParse
supposed to store the value in the given variable if it returns true? My program also works if I assign the textboxes content to their respective variable in the beginning of the first if block. For example: txt_a.Text = a
.