[英]It should be two errors here but I can´t see them
新錯誤:
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();
}
}
您正在考慮將變量 meter 和 bmi 設為 double 類型。 但是,賦值右側的表達式是 int 之間的除法運算,這會導致精度損失。
您需要將右側的一個操作數強制轉換為雙倍以保持精度。
double meter = (double) centimeter / 100;
double bmi = (double) weight / (meter * meter);
在您的System.out.printf
,您使用的是不存在的length
變量。 據我了解,那里應該有meter
變量。
我還修復了第一個System.out.print
Length
字中的錯字。
固定類看起來像這樣(更新:還修復了整數除法,這是實際問題的目標):
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.