这是一个基本的单位转换应用程序。
我刚刚完成编码,一切正常,除了华氏温度和摄氏温度计算。公式是对的,但不知道为什么。
以下是Activity.Java
package arirang.unit.converter;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.EditText;
import android.widget.TextView;
public class BasicUnitConverterActivity extends Activity {
EditText val3;
String val2;
int val1;
String forResult;
Spinner Type;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner1 = (Spinner) findViewById(R.id.Spinner1);
ArrayAdapter adapter1 = ArrayAdapter.createFromResource(
this, R.array.UnitList, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
}
private String changeFormat(Double dbResult) {
String result;
DecimalFormat format = new DecimalFormat();
result = format.format(dbResult);
return result;
}
public void converter(View View) {
EditText val3 = (EditText) findViewById(R.id.BeforeBox);
String val2 = val3.getText().toString();
if (val2.length() > 0) {
val1 = Integer.parseInt(val2);
Type = (Spinner) findViewById(R.id.Spinner1);
double dbResult = 0;
if (Type.getSelectedItem().toString().equals("meter to inch")) {
dbResult = val1 * 39.3700787;
} else if (Type.getSelectedItem().toString().equals("meter to feet")) {
dbResult = val1 * 3.2808399;
} else if (Type.getSelectedItem().toString().equals("feet to inch")) {
dbResult = val1 * 12;
} else if (Type.getSelectedItem().toString().equals("feet to meter")) {
dbResult = val1 / 3.2808399;
} else if (Type.getSelectedItem().toString().equals("inch to meter")) {
dbResult = val1 / 39.3700787;
} else if (Type.getSelectedItem().toString().equals("inch to feet")) {
dbResult = val1 / 12;
} else if (Type.getSelectedItem().toString().equals("kilogram to pound")) {
dbResult = val1 * 2.20462262;
} else if (Type.getSelectedItem().toString().equals("pound to kilogram")) {
dbResult = val1 / 2.20462262;
} else if (Type.getSelectedItem().toString().equals("Fahrenheit to Celsius")) {
dbResult = (val1 - 32) * (5 / 9);
} else if (Type.getSelectedItem().toString().equals("Celsius to Fahrenheit")) {
dbResult = (val1 * (9 / 5)) + 32;
}
forResult = changeFormat(dbResult);
TextView AfterBox = (TextView) findViewById(R.id.AfterBox);
AfterBox.setText(forResult);
}
}
}
答案 0 :(得分:6)
dbResult=(val1 - 32) * (5 / 9);
应该是dbResult=(val1 - 32) * (5f / 9);
问题是当你写5/9时这意味着你要划分int值,因此结果将是0(5小于9所以5/9是。如果它是10/9,结果将是1)。通过向其中一个参数添加一个转换,编译器执行所谓的扩展原语类型转换,并将/运算符的两个参数提升为浮点数。现在,在浮点值之间进行除法,结果将是您期望的结果。
答案 1 :(得分:1)
我肯定会让“val1”成为一个浮点数,并在“双”空间中完成所有数学运算。完成时截断或舍入为整数 - 而不是在计算时。
double val1;
...
dbResult = (val1 * (9.0 / 5.0)) + 32.0;
...
... IMHO