Calculate square root in C#

Asked

Viewed 1,975 times

3

I have a calculator made in WPF C# with basic operations +,-,*,/, % . And now I wanted to try to improve my calculator.

namespace calculadora
 {
 public delegate float? dlgoperacao(float? a, float? b);

public partial class MainWindow : Window
{
    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[+-/*]", System.Text.RegularExpressions.RegexOptions.None);
    const int PESO = 10;
    int? divisor = null;
    bool flag = false;

    float? op1 = 0, op2 = null;
    float? rslt = null;
    dlgoperacao operacao = null;

    public MainWindow()
    {
        InitializeComponent();
        // img.Source = new BitmapImage(new Uri(@"imgs/2.jpg",UriKind.Relative));
    }//Fim Construtor

    protected float? calculaop(float? operori, ref  int? div, char ch)
    {
        float? rslt = null;
        if (ch == ',') { rslt = operori; div = 1; return rslt; }
        else
        {
            int digito = Convert.ToInt32(ch - 48);
            if (div == null) rslt = (operori == null) ? digito : (operori * PESO) + digito;
            else
            {
                div = div * 10;
                rslt = ((operori * div) + digito) / div;

            }
            return rslt;
        }

    }




    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button bt = (Button)sender;
        char[] ch = bt.Content.ToString().ToCharArray();
        if (char.IsDigit(ch[0].ToString(), 0) || ch[0] == ',')
        {
            if (flag)
            {
                op2 = calculaop(op2, ref divisor, ch[0]);
                // int i = regex.Match(txt.Text).Index;
                //txt.Text = txt.Text.Substring(0, i +1) +  " " + op2.ToString();
                txt.Text = op2.ToString();
            }
            else
            {

                op1 = calculaop(op1, ref divisor, ch[0]);
                txt.Text = op1.ToString();
            }

        }//if ch[0] is digit
        else
        {
            divisor = null;
            switch (ch[0])
            {
                case 'c':
                    flag = false;
                    op1 = op2 = null;
                    operacao = null;
                    txt.Text = "";
                    break;
                case '+':
                    if (op2 == null) flag = !flag;
                    else if (operacao != null)
                    {
                        op1 = operacao(op1, op2);
                        op2 = null;
                        flag = true;

                    }
                    operacao = (a, b) => a + b;
                    txt.Text = op1.ToString() + " + ";
                    break;
                case '-':
                    if (op2 == null) flag = !flag;
                    else if (operacao != null)
                    {
                        op1 = operacao(op1, op2);
                        op2 = null;
                        flag = true;
                    }
                    operacao = (a, b) => a - b;
                    txt.Text = op1.ToString() + "-";
                    break;
                case '*':
                    if (op2 == null) flag = !flag;
                    else if (operacao != null)
                    {
                        op1 = operacao(op1, op2);
                        op2 = null;
                        flag = true;
                    }
                    operacao = (a, b) => a * b;
                    txt.Text = op1.ToString() + "*";
                    break;
                case '/':

                    try
                    {
                        if (op2 == null) flag = !flag;
                        else if (operacao != null)
                        {
                            op1 = operacao(op1, op2);
                            op2 = null;
                            flag = true;

                        }
                        operacao = (a, b) => a / b;
                        txt.Text = op1.ToString() + "/";
                    }
                    catch (Exception x)
                    {

                        txt.Text = x.Message;
                    }

                    break;

                case '√':



                    break;

                case '%':

                    try
                    {
                        if (op2 == null) flag = !flag;
                        else if (operacao != null)
                        {
                            op1 = operacao(op1, op2);
                            op2 = null;
                            flag = true;

                        }
                        operacao = (a, b) => a % b;
                        txt.Text = op1.ToString() + "%";
                    }
                    catch (Exception x)
                    {

                        txt.Text = x.Message;
                    }

                    break;


                case '=':
                    if (operacao != null)
                    {
                        if (op2 != null) rslt = operacao(op1, op2);
                        else rslt = op1;
                        txt.Text = "Resultado -> " + rslt.ToString();
                        flag = false;
                        operacao = null;
                        op1 = op2 = null;

                    }
                    break;

            }//switch

        }//else ch[0] -> not digit

    }
}

}

Now I want to put the square root. I don’t know if I will use the case to make it work or if I’ll use another way.

  • The code is partial, post it in full.

  • Complete code

  • Um, why don’t you use Math? use command Sqrt (Example Math.Sqrt(9) and result 3) is root and square is Pow (Example: Math.Pow(9, 2) and result 81).. Follow tutorial http://www.dotnetperls.com/math. and even more!

1 answer

6


Just use the . NET function Sqrt():

if (op2 == null) flag = !flag;
else if (operacao != null) {
    op1 = operacao(op1, op2);
    op2 = null;
    flag = true;
}
operacao = (a, b) => (float?)Convert.ToSingle(Math.Sqrt(a));
txt.Text = op1.ToString() + "√";
break;

I put in the Github for future reference.

I had to make a conversion to float to be compatible with the type used.

You may have to make an adaptation since the square root has only one operand.

Other operations can be added using own formulas and existing . Net functions in the class Math.

I don’t mean to pry, but the code is very confusing, and I doubt you need all this to work. Actually see some problems and it doesn’t even work right.

I believe the correct exception there in others cases would be the DivideByZeroException. Do not use Exception everywhere.

  • Error 1 No Overload for method 'Sqrt' takes 2 Arguments gives me this error s:

  • Oops. I went on automatic, I forgot that the root only has one argument. I edited to reflect this. Then the calculator started to get complicated and the applied logic doesn’t work so well anymore.

  • I had already tried to put only one argument but I have other errors : Error 1 The best overloaded method match for 'System.Math.Sqrt(double)' has some invalid Arguments ; Error 2 Argument 1: cannot Convert from 'float? ' to 'double'

  • Try that last change. The problem is that now you have to go around with tricks to solve problems that would not exist if the code had been well architected. That’s why I commented on this in the answer. It will be a nightmare to move this code.

  • This will be to start learning how to mess with C#. I might try doing this code again. An option is to make a button for each option instead of using the case?

  • The best way to learn is to study the subject. Doing things without much discretion doesn’t help much. Look for a good book http://answall.com/tags/c%23/info and read the questions here on the site. It’s pretty cool: http://answall.com/questions/tagged/c%23? Sort=votes&pageSize=50

Show 1 more comment

Browser other questions tagged

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