我是Java新手并尝试制作基本的体重计算器。 我的问题是我需要问问题,转换测量值然后将其传递给另一个方法,然后以单独的方法显示结果。 我已在下面添加了我的代码,但每次都会返回1.0作为答案。
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();
}
}
答案 0 :(得分:1)
您根本没有在代码中调用bodyMassIndex
方法。变化
displayResults(resultBMI);
到
displayResults(bodyMassIndex(weightInKg, heightInMeters));
resultBMI
等于 1 ,所以当然输出总是:
"The calculated body mass index was: 1"
完整代码:
public static void main(String[] args) {
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);
// You can get rid of the resultBMI variable
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
答案 1 :(得分:0)
你得到1.0因为你硬编码它。
改变这个:
public class Motorcycle : IVehicle
{
#region IVehicle implementation
#endregion
#region Nested Types
public sealed class Helmet
{
public string Color;
public string Size;
public string VisorType;
public bool RequiredByLaw;
}
public Helmet Helmet;
public decimal Mileage;
#endregion
}
要:
double resultBMI = 1;
顺便说一句,你也可以直接在方法中返回BMI, 不再需要乘以1.375 ,因为你已经在KG中提供了体重:
double resultBMI = bodyMassIndex(weightInKG, heightInMeters);
添加:
您从英寸到米的转换也是错误的。它应该是:
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / (heightInMeters*heightInMeters));
}