0

Hello for example I have code something like this:

double mealCost = scan.nextDouble(); // original meal price
int tipPercent = scan.nextInt(); // tip percentage
int taxPercent = scan.nextInt(); // tax percentage
double totalPercent=tipPercent/100*mealCost;

And when I run this code with this data :

 mealCost=20
 tipPercent=12.00
 taxPercent=8

As a result I get 0, but it must be 2.4, and I can't understand why.

Lynx Rufus
  • 71
  • 1
  • 8
  • It is because `tipPercent/100` is integer division, meaning the result is an integer. `tipPercent/100.0` would work; or `double tipPercent = scan.nextInt();` would work too. – Andy Turner Jul 29 '16 at 08:34
  • I think by default Java convert all variables to double if any of the variable in expression is double. – Lynx Rufus Jul 29 '16 at 08:37
  • No, it doesn't. If it did, your answer would be as you expected. – Andy Turner Jul 29 '16 at 08:38
  • If not hard can you give some manual why it happening? – Lynx Rufus Jul 29 '16 at 08:42
  • It happens because that's the way that arithmetic operators are evaluated in Java. The operands of each operator are "promoted" if necessary - but that's only when evaluating the specific operation. Because `/` and `*` have equal precedence, you are effectively evaluating `int tmp = tipPercent / 100; double totalPercent = tmp * mealCost`. In the first expression, both operands are `int`, so integer division occurs. In the second, one operand is `int`, the other is `double`, so the `int` is promoted to a `double`. – Andy Turner Jul 29 '16 at 08:51
  • Thank you it' very clear and understandable. – Lynx Rufus Jul 29 '16 at 09:01

0 Answers0