3

In the code below, when x = 60 and y = 2, result = 500. This is correct, but any x value between 60 and 119 also gives 500. Also, when x < 60, I get a divide by 0 error. Additionally, when x >= 120, result = 0. I am stumped as to why this is happening. I have also tried using various combinations of int, float, and long and still, no luck.

public class main {

    static long result;
    static int x;
    static int y;
    public static void main(String[] args) {
        x = 60;
        y = 2;
        result = 1000 * (1 / (x / 60)) / y;
        System.out.println(result);
    }

}

By the way, I encountered this problem while trying to make a metronome application for Android. I took this code out of context to make it easier to isolate the problem. Any help and/or suggestions are very appreciated!

user1161521
  • 43
  • 1
  • 4
  • 1
    Hint: `int / int -> int`. In addition to promoting to a float/double, consider rewriting it as `(1000 * 60) / (x * y)` - this reduces the error introduced by `1 / (x / 60)`. – user2246674 Sep 10 '13 at 01:19
  • Thanks that should help clean up the code a little bit – user1161521 Sep 10 '13 at 01:21
  • possible duplicate of [Unexpected result of expressions with division](http://stackoverflow.com/questions/16239727/unexpected-result-of-expressions-with-division) – user207421 Sep 10 '13 at 01:24
  • And also [Why does integer division code give the wrong answer?](https://stackoverflow.com/questions/7286681) – Stephen C Jan 23 '22 at 06:11

3 Answers3

6

The answer is not wrong, it's just not what you're expecting. You're using int division which will return an int result, a result that is truncated to the int result.

You want to do double division to get a double result, not int division which returns an int result.

// the 1.0 will allow for floating point division
result = (long) (1000 * (1.0 / (x / 60)) / y); 
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Ok thanks! I've heard of double before and have used it, but I had a massive 2-day brain fart and TOTALLY forgot about that! Too easy – user1161521 Sep 10 '13 at 01:19
1

Integer arithmetics say that

1999 / 100

is in fact 19, not 19.99 or 20, as you might expect.

If you do a division with integers, you will always get the floored result of the actual (mathematical) result.

Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45
1

The equation could be simplified as

result = 1000 * 60 / (x * y);

If you want float division result:

result = long(1000 * 60.0 / (x * y));

If you want rounded float division result:

result = long(1000 * 60.0 / (x * y) + 0.5);
lulyon
  • 6,707
  • 7
  • 32
  • 49