Java 中的除法总是导致零 (0)? [英] Division in Java always results in zero (0)?

查看:28
本文介绍了Java 中的除法总是导致零 (0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The function below gets two values from sharedpreferences, weight and height, and I use these to calculate the BMI, When I print the content of the values I get the values i have entered in the sharedprefs ( which is good) but then when i run a division operation on them, I always get 0 as a result.. Where is the error?

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;

}

推荐答案

你在做整数除法.

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

You need to cast one operand to double.

这篇关于Java 中的除法总是导致零 (0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆