Compute square root with input from typed text

Asked

Viewed 265 times

2

I’m not getting the calculator to take the root of a number that the user types. The most I got was what is in the code, but regardless of the screen value, it only returns the root value of 2 (1,412...) or root of any pre-defined value in the code. I want the program to take the root of the value on the screen.

private void buttonRaiz_Click(object sender, EventArgs e)
    { 
        double label1 = 2;          

        double resutado = Convert.ToSingle(Math.Sqrt(label1));

        Tela.Text = resutado.ToString();

    }

Tela.Text is the name of the calculator screen. label1.Text is the name of a label that I use on the calculator screen to store the numbers. I can only put label1, if by label1.Text error of variable types.

1 answer

4


You first need to convert and then apply the operation to the number. But in the way you’re doing it you can still break the application if something goes wrong:

private void buttonRaiz_Click(object sender, EventArgs e) { 
    if (!double.TryParse(label1, out var valor) //faz alguma coisa aqui para indicar erro
    Tela.Text = Math.Sqrt(valor).ToString();
}

I put in the Github for future reference.

Browser other questions tagged

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