Bhaskara formula in C# with VS 2017

Asked

Viewed 1,149 times

0

Speak People! I’m using Visual Studio to learn C# , I created a button that when clicked should show the result of a Bhaskara formula. But everything that appears on the screen when testing boils down to "Nan"

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace bhaskara
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        /*Fórmula de Bhaskara -- */
        int a = 2, b = 2, c = 4;
        double delta, xl, xll , raizq;

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

        xl = ((-b) + Math.Sqrt(delta)) / 2 * a;
        xll = ((-b) - Math.Sqrt(delta)) / 2 * a;

        MessageBox.Show("O resultado do x linha é :" + xl);
        MessageBox.Show("Já o resultado de x duas linha é:" + xll);
    }
}
}
  • You did a background check for the case : delta < 0 ?

2 answers

8

I reworked your code with some fixes:

1. Verification in case of delta < 0;

2 . Formula correction of delta;

Follow the code with the changes (I reused what I had already written):

/*Fórmula de Bhaskara -- */
        int a = 2, b = 2, c = 4;
        double delta, xl, xll, raizq;

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

        if (delta >= 0)
        {
            MessageBox.Show("O resultado de X1 é :"+((-b) + Math.Sqrt(delta)) / 2 * a);
            MessageBox.Show("O resultado de X2 é: " +((-b) - Math.Sqrt(delta)) / 2 * a);
        }
        else {
            MessageBox.Show("Delta < 0");
        }

0

This code will work:

double n1, n2, n3, resp1, resp2 ;
            n1 = Convert.ToDouble(txtA.Text);
            n2 = Convert.ToDouble(txtB.Text);
            n3 = Convert.ToDouble(txtC.Text);
            resp1 = (-n2 + Math.Sqrt(n2*n2 - 4 * n1 * n3))/ (2 * n1);

            resp2 = (-n2 - Math.Sqrt(n2*n2 - 4 * n1 * n3)) / (2 * n1);

            lblResposta.Text = "X1 = " + resp1.ToString("#0.00") + " X2 = " + resp2.ToString("#0.00");
        }
    }

Browser other questions tagged

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