我正在开发我的第一个解决二次方程式的应用程序,但是遇到一个问题,即当fo a值大于1时,该应用程序会为根提供错误的答案。
这是代码:

package com.example.firstapp;
import java.lang.Math;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

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

    public void calculate(View v){
        EditText number1text = (EditText)findViewById(R.id.a);
        EditText number2text = (EditText)findViewById(R.id.b);
        EditText number3text = (EditText)findViewById(R.id.c);
        double num1 = Double.parseDouble(number1text.getText().toString()) , num2 = Double.parseDouble(number2text.getText().toString()), num3 = Double.parseDouble(number3text.getText().toString());
        if ((num2 * num2) - (4*num1*num3) < 0){

        }

        double ans = (double) ((-(num2)- (Math.sqrt(num2 * num2 - (4*num1*num3))))/2*num1);

        double ans2 = (double) (((-(num2)+ Math.sqrt(num2 * num2 - (4*num1*num3))))/2*num1);


        TextView answer = (TextView)findViewById(R.id.ans1);
        answer.setText("The first root is: " + ans);
        TextView answer2 = (TextView)findViewById(R.id.ans2);
        answer2.setText("The second root is: " + ans2);

    }


    private TextView getText(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


任何有关为什么发生这种情况的帮助都将非常有用。

提前致谢

最佳答案

正确的公式是-b ± sqrt(b^2 - 4ac) / (2a)

您有-b ± sqrt(b^2 - 4ac) / 2 * a

括号将帮助大约2 * num1

07-28 01:44