Division in Java always results in zero (0)? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-11-26 02:14:45

问题


This question already has an answer here:

  • Double value returns 0 [duplicate] 3 answers

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;

}

回答1:


You're doing integer division.

You need to cast one operand to double.




回答2:


You are doing an integer division, cast the values to float and change the datatype of the variable bmi to float.

Like this:

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

You should also change the return type of your method public int computeBMI() to float.

I recommend you to read this stackoverflow question.

Here you have a list of the Primitive Data Types in Java with its full description.

Hope it helps!




回答3:


Because bmi is an integer. Either declare bmi or Weight, Height as floating point numbers. When you use integers in a division, you will get integer division. When you use doubles/floats, you will get floating point division



来源:https://stackoverflow.com/questions/10455677/division-in-java-always-results-in-zero-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!