新错误:
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length in meters: ");
double length = input.nextDouble();
System.out.print("Weight in kilos: ");
double weight = input.nextDouble();
double bmi = weight / length * length;
System.out.printf("BMI");
input.close();
}
}
答案 0 :(得分:1)
您正在考虑变量meter和bmi是double类型。但是,赋值右侧的表达式是int之间的除法运算,这会导致精度损失。
您需要将右侧的操作数之一转换为两倍以保持精度。
double meter = (double) centimeter / 100;
double bmi = (double) weight / (meter * meter);
答案 1 :(得分:0)
在您的System.out.printf
中,您使用的是不存在的length
变量。据我了解,那里应该有meter
变量。
我还修复了System.out.print
字首Length
中的错字。
固定类如下( UPDATE:还固定整数除法,这是实际问题的目标):
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length in centimeter: ");
int centimeter = input.nextInt();
double meter = ((double) centimeter) / 100; // fixed integer division by casting to double
System.out.print("Weight in whole kilo: ");
int weight = input.nextInt();
double bmi = ((double) weight) / (meter * meter); // fixed integer division by casting to double
System.out.printf("BMI for someone who is %.2f meter long, and weight %d kilo is %.1f", meter, weight, bmi);
input.close();
}
}