繁体   English   中英

这里应该是两个错误,但我看不到它们

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM