简体   繁体   中英

Error when adding parenthesis in multiplying int and double in java why?

This is a working code but I am wondering after a full research on multiplying ints and doubles in Java I still can't see why the snippet below the code would give an error. Any help please?

public class Arithmetic {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double mealCost = scan.nextDouble(); // original meal price
        int tipPercent = scan.nextInt(); // tip percentage
        int taxPercent = scan.nextInt(); // tax percentage
        scan.close();

        // Calculate Tax and Tip:
        double tip = mealCost * tipPercent / 100; //HERE IS MY PROBLEM
        double tax = mealCost * taxPercent / 100; //HERE IS MY PROBLEM

        // cast the result of the rounding operation to an int and save it as totalCost 
        int totalCost = (int) Math.round(mealCost + tax + tip);

        System.out.println("The total meal cost is " + totalCost + " dollars.");
    }
}

Knowing that this answer is more logical and gives a different value than the one above?!

double tip = meal * (tipPercent/100);
double tax = meal * (taxPercent/100);

In your 1st example, the multiplication is performed first, resulting in a double number that is then divided by 100, giving the correct double result:

mealCost * tipPercent / 100;

In your 2nd version, an integer division is performed first, resulting in an integer result. Assuming that tipPercent less than 100, the result will be zero.

If you like the second version better, just use a floating point constant:

double tip = meal * (tipPercent/100.0);

Let's imagine:

int tipPercent = 10;
double mealCost = 100.123d;

And

double tip = mealCost * tipPercent / 100;


1. 100.123( double ) * 10( int ) = 1001.23( double )
2. 1001.23( double ) / 100( int ) = 10.0123( double )

In the second:

double tip = mealCost * (tipPercent / 100);
  1. 10( int ) / 100( int ) = 0( int )
  2. 100.123( double ) * 0 = 0( double )

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