简体   繁体   English

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

[英]It should be two errors here but I can´t see them

New error:新错误:

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();
    }
} 

You're considering variables meter and bmi to be of type double.您正在考虑将变量 meter 和 bmi 设为 double 类型。 However, the expression on the right hand side of assignment is divide operation among int which will cause precision loss.但是,赋值右侧的表达式是 int 之间的除法运算,这会导致精度损失。

You'll need to cast one of the operands on right hand side to double to preserve precision.您需要将右侧的一个操作数强制转换为双倍以保持精度。

double meter = (double) centimeter / 100;
double bmi = (double) weight / (meter * meter);

In your System.out.printf , you're using the non-existing length variable.在您的System.out.printf ,您使用的是不存在的length变量。 As I understand, there should be meter variable there.据我了解,那里应该有meter变量。

I've also fixed a typo in first System.out.print in Length word.我还修复了第一个System.out.print Length字中的错字。

The fixed class looks like this ( UPDATE: also fixed the integer division, which was the actual question's target):固定类看起来像这样(更新:还修复了整数除法,这是实际问题的目标):

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