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

时间:2012-05-04 20:25:37

标签: 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;

}

3 个答案:

答案 0 :(得分:43)

您正在进行整数除法。

您需要将一个操作数强制转换为double

答案 1 :(得分:16)

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

像这样:

float bmi = (float)weight/(float)(height*height);

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

我建议你阅读this stackoverflow问题。

Here您在Java中列出了原始数据类型及其完整说明。

希望它有所帮助!

答案 2 :(得分:1)

因为bmi是一个整数。将bmiWeight, Height声明为浮点数。在分区中使用整数时,将得到整数除法。当你使用双打/浮点数时,你将得到浮点除法

相关问题