我正在为Android创建一个计算器,至今它看起来已经完成了很多......事情是答案不准确,加法,减法,乘法工作正常,因为小数通常不是必需的。划分的答案四舍五入到最接近的整数,而不是显示在十进制答案...所以我改变了TextView类型显示小数,并使用浮点数而不是int为包含答案的变量。结果是我以结尾为“.00”的四舍五入整数结尾:/ 请帮忙! 我的代码: MainActivity.java:Android开发,Java中的精确计算?
package in.rohanbojja.basiccalculator;
import android.app.Activity;
import android.os.Bundle;
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);
}
@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;
}
public void add(View view){
EditText n1 = (EditText) findViewById(R.id.editText1);
EditText n2 = (EditText) findViewById(R.id.editText3);
TextView res = (TextView) findViewById(R.id.textView1);
String sn1 = n1.getText().toString();
String sn2 = n2.getText().toString();
String sres;
int in1 = Integer.parseInt(sn1);
int in2 = Integer.parseInt(sn2);
float ires;
ires = in1 + in2;
sres = Float.toString(ires);
res.setText(sres);
}
public void sub(View view){
EditText n1 = (EditText) findViewById(R.id.editText1);
EditText n2 = (EditText) findViewById(R.id.editText3);
TextView res = (TextView) findViewById(R.id.textView1);
String sn1 = n1.getText().toString();
String sn2 = n2.getText().toString();
String sres;
int in1 = Integer.parseInt(sn1);
int in2 = Integer.parseInt(sn2);
float ires;
ires = in1 - in2;
sres = Float.toString(ires);
res.setText(sres);
}
public void mul(View view){
EditText n1 = (EditText) findViewById(R.id.editText1);
EditText n2 = (EditText) findViewById(R.id.editText3);
TextView res = (TextView) findViewById(R.id.textView1);
String sn1 = n1.getText().toString();
String sn2 = n2.getText().toString();
String sres;
int in1 = Integer.parseInt(sn1);
int in2 = Integer.parseInt(sn2);
float ires;
ires = in1 * in2;
sres = Float.toString(ires);
res.setText(sres);
}
public void clr(View view){
EditText n1 = (EditText) findViewById(R.id.editText1);
EditText n2 = (EditText) findViewById(R.id.editText3);
TextView res = (TextView) findViewById(R.id.textView1);
n1.setText("");
n2.setText("");
res.setText("Result");
}
public void div(View view){
EditText n1 = (EditText) findViewById(R.id.editText1);
EditText n2 = (EditText) findViewById(R.id.editText3);
TextView res = (TextView) findViewById(R.id.textView1);
String sn1 = n1.getText().toString();
String sn2 = n2.getText().toString();
String sres;
int in1 = Integer.parseInt(sn1);
int in2 = Integer.parseInt(sn2);
float ires;
ires = in1/in2;
sres = Float.toString(ires);
res.setText(sres);
}
}
你需要做的在Java中的号码类型和数学一些阅读一般。 – kabuko 2013-04-11 19:51:38