我是Java的新手,試圖製作一個基本的體重計算器。 我的問題是我需要問的問題,轉換測量,然後將其傳遞給另一種方法,然後以單獨的方法顯示結果。 我已經在下面添加了我的代碼,但每次都收到1.0返回的答案。基本的Java,在方法之間傳遞數據
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds/2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches/0.254);
double resultBMI = 1;
displayResults(resultBMI);
}
public static double bodyMassIndex(double weightInKg, double
heightInMeters)
{
double resultBMI = weightInKg/Math.pow(heightInMeters, 2) * 1.375;
return resultBMI;
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
更新代碼,現在越來越; 磅輸入重量:180 以英寸輸入高度:68 計算的身體質量指數是:1.1415618118905313E -5- 生成成功(總時間:3秒)
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds/2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches/0.0254);
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg/Math.pow(heightInMeters, 2));
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
我還需要使用printf的方法將BMI結果四捨五入到1位小數...我已經嘗試添加代碼System.out.printf(「計算出的體重指數爲: %.1f「+ resultBMI);但是我這樣做時出現錯誤 – Newb2Java
首先更正您的高度計算。然後用'160磅'和'70英寸'測試重量和身高。你應該得到'BMI 23'。它會工作。 – user3437460
聖潔的蝙蝠俠它的工作原理。有什麼想法,我可以如何四捨五入到一位小數? – Newb2Java