我正在尝试制作一个数学应用程序,并使用此代码我使用我总是得到相同的答案与不同的数字。程序运行正常,它加载,我可以输入数据但总是得到答案0.0。
((- numB + Math.sqrt((Math.pow(numB, 2))-4*numA*numC))/2*numA)
完整代码
public class MainActivityQuadraticEquation extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_quadraticequation);
Button btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Log.i("Click Occured","You Clicked the Back button");
Intent myIntent = new Intent(MainActivityQuadraticEquation.this, MainActivity.class);
startActivity(myIntent);
}
});
}
public void Calculate(View v)
{
EditText inputA = (EditText)findViewById(R.id.InputA);
EditText inputB = (EditText)findViewById(R.id.InputB);
EditText inputC = (EditText)findViewById(R.id.InputC);
Integer numA = Integer.parseInt(inputA.getText().toString()), numB = Integer.parseInt(inputB.getText().toString()), numC = Integer.parseInt(inputC.getText().toString());
Integer ans_1 = (int) ((- numB + Math.sqrt((Math.pow(numB, 2))-4*numA*numC))/2*numA);
Integer ans_2 = (int) ((- numB - Math.sqrt((Math.pow(numB, 2))-4*numA*numC))/2*numA);
double ans_1a = ans_1;
double ans_2a = ans_2;
String ans1 = String.valueOf(ans_1a);
String ans2 = String.valueOf(ans_2a);
TextView answer1 = (TextView)findViewById(R.id.Ans);
TextView answer2 = (TextView)findViewById(R.id.Ans2);
answer1.setText("Answer 1: " + ans1);
//System.out.println("Answer 1: " + ans1);
answer2.setText("Answer 2: " + ans2);
//System.out.println("Answer 2: " + ans2);
}
@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;
}
}
确实如此,但它不起作用
答案 0 :(得分:2)
你的问题不在于数学。可能是解析出现问题或者TextEdit
对象的行为不符合您的预期,但the calculation itself should work:
int numA = 1;
int numB = -6;
int numC = 8;
double ans_1 = (-numB + Math.sqrt(numB * numB - 4 * numA * numC)) / (2 * numA);
double ans_2 = (-numB - Math.sqrt(numB * numB - 4 * numA * numC)) / (2 * numA);
System.out.println(ans_1 + "\n" + ans_2);
输出:
4.0
2.0
当然,正如所建议的那样,你应该坚持使用双打来完成所有这些。此外,还不清楚如何处理没有真正解决方案的情况(使用负数调用Math.sqrt
时)。此外,它似乎在这里工作(令人惊讶),但你应该/2*numA
而不是/(2 * numA)
。
答案 1 :(得分:0)
你的中间演员可能会失去int
的精确度。您也可以将这些整数值读取为双精度数,而不会在计算中失去任何精度。
因此,代码的关键部分就是:
double numA = Double.parseDouble(inputA.getText().toString()),
numB = Double.parseDouble(inputB.getText().toString()),
numC = Double.parseDouble(inputC.getText().toString());
double ans_1 = ((- numB + Math.sqrt((Math.pow(numB, 2))-4*numA*numC))/2*numA);
double ans_2 = ((- numB - Math.sqrt((Math.pow(numB, 2))-4*numA*numC))/2*numA);
String ans1 = String.valueOf(ans_1);
String ans2 = String.valueOf(ans_2);
int
和/或Integer
的中间演员阵容无益且无必要。
答案 2 :(得分:0)
ans_1
和ans_2
投放到int
。您正在失去精确度,将其分配给double
。
double ans_1 = ((-numB ...)
b^2 - 4ac
必须是> 0所以Math.sqrt()
可以工作。 我没有看到任何问题。