2016-10-09 183 views
-2

請耐心等待,我是Java課程第2周的互動設計學生。使用指標計算Java中的BMI

我需要使用下面的公式來創建BMI計算器:使用下面的公式計算BMI:

  w 
BMI = ___ 
     (h/100) 2 

其中w爲體重(公斤)和h爲以釐米爲單位的高度。請注意分母是平方的。

這裏是我的代碼:

/** 
* Calculates the Body Mass Index (BMI) for the user. The user must type in his 
* or her height in centimeters and weight in kilograms, and the computer prints 
* out the user's BMI. 
*/ 
import java.util.Scanner; // import class 
public class BMI { 
    public static void main(String[] args) { 
     int weight; 
     int height; 
     double bmi; 
     Scanner console; // create a variable to represent the console 
     console = new Scanner (System.in); // create the object with new 
     System.out.print("How much do you weigh (in kg)? "); // user prompt to provide weight 
     weight = console.nextInt(); // read from console 
     System.out.print("How tall are you (in cm)? "); // user prompt to provide height 
     height = console.nextInt(); // read value from console 
     bmi = (double) weight/(height/100*height/100); // calculates BMI 
     System.out.println("Your BMI is " + bmi); // displays user's BMI 
    } 
} 

如果可以稱呼它,運行,但我覺得寫的計算不正確的程序。

我已經格式化的計算幾種方法: BMI =(雙)重量/(高度/ 100 *高度/ 100);當我使用100的重量和200的高度時,除了返回重量外。我已嘗試以下步驟:

BMI =(雙)體重/身高/ 100 *高度/ 100;

bmi =(double)weight /(height/100 * height/100);

BMI =(雙)重量/(身高/ 100)*(高度/ 100);

BMI =(雙)重量/((高度/ 100)*(高度/ 100));

bmi =(double)(weight/height/100 * height/100);

BMI =(雙)(重量/(身高/ 100 *高度/ 100);

BMI =(雙)(重量/(身高/ 100)*(高度/ 100);

bmi =(double)(weight)/(height/100)*(height/100));

bmi =(double)(weight)/(height/100)*(height/100)

BMI =(雙)(重量)/身高/ 100 *高度/ 100;

我要麼GE噸重量的100%的時間或它只適用於100和200作爲變量。我嘗試了75和150,這也會使體重恢復。

在這一點上,我甚至不記得PEMDAS

+0

'bmi =重量/(身高/ 100.0 *身高/ 100.0);' –

回答

1

當你劃分INT height 100截斷它的小數,因爲它仍然是一個int。

嘗試初始化變量雙打:

double weight; 
double height; 

然後投下他們,當你從輸入獲得INT:

weight = (double) console.nextInt(); 
height = (double) console.nextInt(); 

這樣,你還在考慮一個int爲輸入,但是當你進行你的計算時,它的行爲就像是雙重的。

+0

工作,謝謝! –

1

使用簡化的公式來獲得所需的結果。試試這個: bmc=(weight * 10000.0) /(height*height); 不需要任何鑄造就好像表達式中有任何雙數(10000.0)那麼它會自動返回結果加倍。