java Math.Sqrt(x); 不工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11742981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:12:31  来源:igfitidea点击:

Math.Sqrt(x); not working?

javaandroidmathsqrt

提问by Chris

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.

只是为了提供一些关于此的信息,x 是一个 CharSequence,xconv 是将 x 转换为 double,而 answer 是一个字符串值。谢谢。

回答by Kaediil

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

那是因为 Math.sqrt返回的是 sqrt,它不会修改传入的值。

xconv = Math.sqrt(xconv);

is what you want.

是你想要的。

回答by Ram kiran

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

实际的问题是你只留下结果而不存储在任何变量中。

Just initiate the square rootresult to xconvand then see you can get result.

只需将square root结果启动到xconv,然后查看您就可以得到结果。

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);

    }});

回答by Chris Dargis

double squareRoot = Math.sqrt(xconv);

回答by Fritz

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

您没有存储 Math.sqrt 的值。变量不会更新,而是返回结果。做类似的事情:

xconv = Math.sqrt(xconv);

回答by Paul John Rigor Padrigo

x=Double.parseDouble(edtchar.getText().toString());
ans.setText(Double.toString(Math.sqrt(x)));

consider x as the Double and ans as the textview.

将 x 视为 Double 并将 ans 视为文本视图。