Java中的除法總是導致零(0)嗎?下面的函數從sharedpreferences中獲取兩個值,即weight和height,我用它們來計算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 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
因為bmi
是整數。聲明bmi
或Weight, Height
作為浮點數。在除法中使用整數時,將獲得整數除法。使用double / floats時,將得到浮點除法
添加回答
舉報
0/150
提交
取消