简体   繁体   中英

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. However, the expression on the right hand side of assignment is divide operation among int which will cause precision loss.

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. As I understand, there should be meter variable there.

I've also fixed a typo in first System.out.print in Length word.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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