Math.Sqrt(x); not working?

18,231

Solution 1

That is because Math.sqrt returns the sqrt, it does not modify the passed in value.

xconv = Math.sqrt(xconv);

is what you want.

Solution 2

The actual problem is you just leave the result without storing in any variable.

Just initiate the square root result to xconv and then see you can get result.

Replace your code with my code

 SquareRoot = (Button)findViewById(R.id.SquareRoot);
    SquareRoot.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            x = TextBox.getText();
            xconv = Double.parseDouble(x.toString());
            xconv = Math.sqrt(xconv);//======> you are not initalize the answer to a variable here
            answer = Double.toString(xconv);
            TextBox.setText(answer);

    }});

Solution 3

double squareRoot = Math.sqrt(xconv);

Solution 4

You're not storing the value of Math.sqrt. The variable is not updated but the result is returned instead. Do something like:

xconv = Math.sqrt(xconv);
Share:
18,231
Chris
Author by

Chris

Updated on July 20, 2022

Comments

  • Chris
    Chris almost 2 years

    I'm making a calculator and when trying to make the square root function, it outputs the number you put in, not the square root. Here's the bit of code that applies to the square root function.

    SquareRoot = (Button)findViewById(R.id.SquareRoot);
            SquareRoot.setOnClickListener(new OnClickListener() {
                 public void onClick(View v) {
                    x = TextBox.getText();
                    xconv = Double.parseDouble(x.toString());
                    Math.sqrt(xconv);
                    answer = Double.toString(xconv);
                    TextBox.setText(answer);
    
            }});
    

    Just to give some information on this, x is a CharSequence, xconv is x converted to double, and answer is a string value. Thanks.