Bhaskara beginner

Asked

Viewed 198 times

3

When I compile this code, it appears: a1 vale NaN(Não é um número) and then: a2 vale NaN(Não é um número), follows the code:

private void button1_Click(object sender, EventArgs e)
{
    int a = 2;
    int b = 3;
    int c = 5;

    double delta;
    double a1;
    double a2;

    delta = (b * b) - 4 * a * c;
    a1 = (-b + Math.Sqrt(delta)) / (2 * a);
    a2 = (-b - Math.Sqrt(delta)) / (2 * a);

    MessageBox.Show("a1 vale " + a1);
    MessageBox.Show("a2 vale " + a2);

}
  • 4

    Root of a negative number does not give real number. That’s the problem

  • 5

    you should check the delta value before continuing. If Δ = 0 there will only be a root If Δ < 0 , it will have no roots. If Δ > 0 , will have two different real roots.

2 answers

3

Negative root is NAN

9 - 40 is -31, and this is the value of delta

Following your code line of reasoning (which is to show message with the answer) you could put the following test:

if (delta < 0) {
    MessageBox.Show("Essa função não possui zeros reais");
    return;
}

1

As the result that searched in delta is a negative number you can program its function to also adapt and thus show the result taking into account the complex numbers. The calculation of a negative root is simple just multiply it by -1 and at the end of the operation add an "i" that signals the complex number, so we get something like this:

private void button1_Click(object sender, EventArgs e)
{
    int a = 2;
    int b = 3;
    int c = 5;

    double delta;
    double a1;
    double a2;

    delta = (b * b) - 4 * a * c;

    if (delta < 0)
    {
    delta *=-1;
    a1 = (-b + Math.Sqrt(delta)) / (2 * a);
    a2 = (-b - Math.Sqrt(delta)) / (2 * a);

    MessageBox.Show("utilizando-se da propriedade dos numeros complexo obtemos que:");
    MessageBox.Show("a1 vale " + a1+"i");
    MessageBox.Show("a2 vale " + a2+"i");
    }

    else
    {
    a1 = (-b + Math.Sqrt(delta)) / (2 * a);
    a2 = (-b - Math.Sqrt(delta)) / (2 * a);

    MessageBox.Show("a1 vale " + a1);
    MessageBox.Show("a2 vale " + a2);
    }

}
  • I liked the way you got around the root problem. Maybe it would be even better to use the complex type that the language has

Browser other questions tagged

You are not signed in. Login or sign up in order to post.