0
class Result {

    public static void solve(double meal_cost, int tip_percent, int tax_percent) {
       
    double tax=(meal_cost*tax_percent)/100;
    double tip=(meal_cost*tip_percent)/100;
    double total=meal_cost+tax+tip;
    
    System.out.println(Math.round(total));
    }

}

From the code above the result comes out 15

But,

class Result {

    public static void solve(double meal_cost, int tip_percent, int tax_percent) {
       
    double tax=(tax_percent/100)*meal_cost;
    double tip=(meal_cost/100)*tip_percent;
    double total=meal_cost+tax+tip;
            
    System.out.println(Math.round(total));    }

}

in this the result was 14 Why?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 2
    `tax_percent` is an `int` variable, hence, `tax_percent/100` performs an integer division, which implictly rounds down the result. – Holger May 12 '23 at 11:49
  • 1
    Since you tagged your question with “optimization”: your change of operation order wouldn’t improve anything anyway. If you want to optimize the operation, you should consider that you don’t need `tax` nor `tip` but only the sum of them. So instead of doing the same percentage calculation twice, you can sum the percentages first and calculate the absolute value once: `double taxAndTip = meal_cost*(tip_percent + tax_percent)/100, total=meal_cost+taxAndTip;` Since you’re rounding, the expert solution could be something like `total = meal_cost * Math.fma(tip_percent + tax_percent, 0.01, 1)`. – Holger May 12 '23 at 12:15
  • 1
    When doing integer math, the order can matter. This can change if floating point values are being used but can still lead to wrong answers if you're not careful. Using left to right evaluation since `*` and `/` have the same precedence, `9/10*100` will be `0*100` which is `0`. But `100*9/10` will be `900/10` which is `90`. The key point to remember is that `int division drops fractions`. – WJS May 12 '23 at 13:20

0 Answers0