0

could someone explain me what am I doing wrong here, and how can I make this formula to be working? right now it returns 0 in Java and Pawn. But it works in PHP, which isnt making much sense for me.

int test = (65 / 65 / (1 + 25) * 10000);
  • 6
    That's because in PHP all the arithmetic is floating-point, and this Java snippet is working with integers. – gvlasov Mar 06 '15 at 02:21
  • 1
    I'm not sure what's going wrong, but in Java integer division will truncate the results. Try `(65.0 / 65.0 / (1.0 + 25.0) * 10000.0);` for floats. – eigenchris Mar 06 '15 at 02:21
  • 1
    possible duplicate of [Division of integers in Java](http://stackoverflow.com/questions/7220681/division-of-integers-in-java) – gknicker Mar 06 '15 at 02:25
  • Thank you guys, @eigenchris , that's what I've been looking for. Post your Answer so I can mark it as the answer. – Patryk Cieszkowski Mar 06 '15 at 02:28
  • And thanks to all of you! :) – Patryk Cieszkowski Mar 06 '15 at 02:28
  • More well placed parentheses will make it work more like the way you want. Java of course has defined rules as to order of evaluation, but *never* depend on such rules in a language. Force your desired order of evaluation with parentheses. – Alan Mar 06 '15 at 02:36

2 Answers2

2

In Java, integer division will truncate the results. For example, 5/2 will truncate 2.5 to 2.

To ensure you're using float with numeric constants, add a .0 on the end, as in:

int test = (65.0 / 65.0 / (1.0 + 25.0) * 10000.0);
eigenchris
  • 5,791
  • 2
  • 21
  • 30
2

Java operations for multiplication and division is left to right, so your expression is really:

(((65 / 65) / 26) * 1000)  // Clarifying parenthesis
((1 / 26) * 1000)          
(0 * 1000)                 // integer division!
0

To avoid this, you just need to ensure the operations are casted to a double.

The simple way would be just changing the first value to a double, either by:

int test = (65D / 65 / (1 + 25) * 10000);

Or

int test = (65.0 / 65 / (1 + 25) * 10000);

However, if you are refactoring your code later, you might want to change more than just the first value.

Obicere
  • 2,999
  • 3
  • 20
  • 31