Chr*_*ris 2 java math android sqrt
我正在制作一个计算器,在尝试制作平方根函数时,它输出你输入的数字,而不是平方根.这是适用于平方根函数的代码.
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);
}});
Run Code Online (Sandbox Code Playgroud)
只是为了给出一些信息,x是CharSequence,xconv是x转换为double,而answer是一个字符串值.谢谢.
Kae*_*iil 13
这是因为Math.sqrt 返回 sqrt,它不会修改传入的值.
xconv = Math.sqrt(xconv);
Run Code Online (Sandbox Code Playgroud)
是你想要的.
实际问题是你只是保留结果而不存储任何变量.
只需启动square root
结果xconv
,然后看到你可以得到结果.
用我的代码替换你的代码
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);
}});
Run Code Online (Sandbox Code Playgroud)