2012-07-31 60 views
2

我正在做一個計算器,當試圖做平方根函數時,它輸出你輸入的數字,而不是平方根。以下是適用於平方根函數的一些代碼。Math.Sqrt(x);不工作?

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

     }}); 

只給這方面的一些信息,x是一個的CharSequence,xconv爲x轉換爲翻一番,答案是一個字符串值。謝謝。

+3

xconv = Math.sqrt(xconv); – Shark 2012-07-31 15:10:04

回答

13

這是因爲Math.sqrt 返回 sqrt,它不會修改傳入的值。

xconv = Math.sqrt(xconv); 

是你想要的。

2

您不存儲Math.sqrt的值。該變量未更新,但返回結果。這樣做:

xconv = Math.sqrt(xconv); 
3
double squareRoot = Math.sqrt(xconv); 
5

實際的問題是你剛剛離開的結果沒有任何變量存儲。

只需發起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); 

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

考慮x作爲雙和ANS作爲TextView的。