Java中的除法总是导致零(0)?

cal*_*ack 14 java android division

下面的函数从共享偏好,权重和高度中获取两个值,我使用它们来计算BMI,当我打印值的内容时,我得到我在sharedprefs中输入的值(这很好)但是当我运行时对它们进行除法运算,结果总是得到0 ..错误在哪里?

public int computeBMI(){
    SharedPreferences customSharedPreference = getSharedPreferences(
            "myCustomSharedPrefs", Activity.MODE_PRIVATE);

    String Height = customSharedPreference.getString("heightpref", "");
    String Weight = customSharedPreference.getString("weightpref", "");

    int weight = Integer.parseInt(Weight);
    int height = Integer.parseInt(Height);
    Toast.makeText(CalculationsActivity.this, Height+" "+ Weight , Toast.LENGTH_LONG).show();

    int bmi = weight/(height*height);
    return bmi;

}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 46

你正在进行整数除法.

你需要将一个操作数转换为double.


Cac*_*nta 18

您正在进行整数除法,将值float转换为并将变量的数据类型更改bmifloat.

像这样:

float bmi = (float)weight/(float)(height*height);
Run Code Online (Sandbox Code Playgroud)

您还应该将方法的返回类型更改public int computeBMI()float.

我建议你阅读这个 stackoverflow问题.

这里有一个Java 中的原始数据类型列表及其完整描述.

希望能帮助到你!