2

is something wrong with my code below?

public class testing111 {
   public static void main(String[] args) {
      int t = 0;
      System.out.println((t-5)%360);      
  }

}

My code above outputs -5. I thought the answer should be 355 and I even checked wolframalpha: http://www.wolframalpha.com/input/?i=%280-5%29%25360

What is causing it to do this?

Thanks!

Giga Tocka
  • 191
  • 3
  • 3
  • 11

1 Answers1

3

It seems like WolframAlpha and Java behaves differently here.

In Java, you can get a negative result from the modulo operator. Think "If I divide -5 by 360 and take the remainder of that", since -5 / 360 is 0, you are left over with -5 that simply couldn't be divided. And so the result in Java is -5.

If you want the answer that WolframAlpha produces, you should add 360 if the result from the modulo operator is less than 0.

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108