0

大家好,我是 android 新手,想在这里显示二次公式计算是我在 android 中执行的代码,此代码中没有显示错误,但仍然在模拟器上它不显示结果:-(

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button b1 = (Button) findViewById(R.id.btnSubmit);
    final EditText et1 = (EditText) findViewById(R.id.etVA);//whats wrong
    final EditText et2 = (EditText) findViewById(R.id.etVC);//whats wrong
    final EditText et3 = (EditText) findViewById(R.id.etVC);//whats wrong
    final TextView answer = (TextView) findViewById(R.id.txtResult);//whats wrong
    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String a1 = et1.getText().toString();//whats wrong
            double a = Double.parseDouble(a1);//whats wrong

            String b1 = et2.getText().toString();//whats wrong
            double b = Double.parseDouble(b1);//whats wrong

            String c1 = et3.getText().toString();//whats wrong
            double c = Double.parseDouble(c1);//whats wrong

            double x1 = (-b+Math.sqrt(b*b-4*a*c))/(2*a);//whats wrong

            System.out.println("x1 = "+ x1);

            String R = x1+ "";  //whats wrong
            answer.setText("Your Answer is " + R); //whats wrong
        }
    });
}
4

4 回答 4

2

试试这样

        String a1 = et1.getText().toString();
        double a =  Double.valueof(a1);

        String b1 = et2.getText().toString();
        double b =  Double.valueof(b1);

        String c1 = et3.getText().toString();
        double c = Double.valueof(c1);

        double x1 = (-b+Math.sqrt(b*b-4*a*c))/(2*a);

        System.out.println("x1 = "+ x1);

        String R = String.valueof(x1);
        answer.setText("Your Answer is " + R); 
于 2013-04-23T11:40:03.357 回答
1

我找到了解决方案。代码很好,但我只是犯了一个简单的逻辑错误

final EditText et1 = (EditText) findViewById(R.id.etVA); 
final EditText et2 = (EditText) findViewById(R.id.etVC);//that is the mistake it should be like (R.id.etVB).... 
final EditText et3 = (EditText) findViewById(R.id.etVC); 
于 2013-06-26T07:00:47.213 回答
1

您的程序没有任何错误,您必须提供有效的输入。否则,您将得到输出Your Answer is NAN即 Not a Number。

从某种意义上说,有效输入,提供的 a、b 和 c 的值必须满足方程ax 2 + bx + c = 0。这样就可以用二次公式求根了。

示例有效输入:

a = 1.0
b = 3.0
c = 2.0

上述输入的输出:

Your Answer is -1.0
于 2013-04-23T12:11:48.727 回答
0

通过 View 调用 onclicklistner()

        b1.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });
于 2013-04-23T11:47:41.050 回答