0

I've been writing this code to do the quadratic formula for me, but there's a problem found a problem right here:

        if (textBox2.Text != "")
        {
        string h = textBox2.Text;
        double c = double.Parse(h);
        }
        else if (textBox2.Text == "")
        {
        double c = 0;
        }
        // else error message

        //Delta
        double delta = (Math.Pow(b, 2)) - (4 * a * c);
        string dtxt = Convert.ToString(delta);

        label5.Text = dtxt;

The problem is, "The name 'c' doesn't exist in current context". That also happens with the values b, and a, which have the same conditions as c.

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
  • A variable declared inside a block `{ ... }` has local scope. It is not available outside of that block. Declare your variables once and for all before entering the ifs. It is basic and perhaps you should stop here and read a book on this. – Steve Oct 31 '15 at 16:11
  • Move the declaration of `c` to the top of your code scope. – Anthony Sherratt Oct 31 '15 at 16:12

4 Answers4

0

You’re declaring those variables inside the if block so they cease to exist at the end of it.

You can use the following initialisation instead:

double c = (textBox2.Text == "") ? 0 : double.Parse(textBox2.Text);

That way, c is declared in the same scope it’s used in.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

c is defined in its own block:

    {
    double c = 0;
    }

so c can only be accessed within that block. Outside of it it isn't visible.

Joey
  • 344,408
  • 85
  • 689
  • 683
0

You should move declaration of c outside the if:

double c;
if (textBox2.Text != "")
{
    string h = textBox2.Text;
    c = double.Parse(h);
}
else
{
    c = 0;
}

Moreover, you could replace this block with 1 line:

double c = textBox2.Text.Length != 0 ? Double.Parse(textBox2.Text) : 0;
Dmitry
  • 13,797
  • 6
  • 32
  • 48
0

It is a scope issue as the error suggest, you need to declare the double before the if statement:

double c;

if (textBox2.Text != "")
{
string h = textBox2.Text;
c = double.Parse(h);
}
else if (textBox2.Text == "")
{
c = 0;
}
// else error message

//Delta
double delta = (Math.Pow(b, 2)) - (4 * a * c);
string dtxt = Convert.ToString(delta);

label5.Text = dtxt;
meda
  • 45,103
  • 14
  • 92
  • 122