1

At the moment in one of my projects that I am working on, I need to check if a value falls between a number divisible by 12 and a number divisible by 12 + 5.

 if (Number >= 0 && Number <= 5) {
            value = 0;
 } else if (Number >= 12 && Number <= 17) {
            value = 12;
 } else if (Number >= 24 && Number <= 29) {
            value = 24;
 }
 // etc...

The code above works perfectly but I feel that it could be cut down. Does anyone have an alternative way of how to achieve what I am going for but more elegantly?

Hayden
  • 407
  • 1
  • 6
  • 15

1 Answers1

8

Use the % operator. (See http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx)

This should work as long as Number is positive; if it's not you'll have to look into how % works for negative numbers:

if (Number % 12 <= 5) {
    value = 12*(int)(Number/12);
}
ahuff44
  • 1,100
  • 1
  • 9
  • 9
  • Thank you so much. I need to wait 8 minutes until I can give you best answer. I don't know why I didn't think of that. – Hayden Jun 02 '13 at 03:29
  • 1
    should that be (int)(Number ... ) instead of int(Number...) – Scott Selby Jun 02 '13 at 03:30
  • 1
    All integers mod 12 will be >=0, so there shouldn't be a reason to check for it. – Robert McKee Jun 02 '13 at 05:08
  • Erm, well, unless `number` was negative, then it could could be less than 0 actually – Robert McKee Jun 02 '13 at 05:17
  • Yeah, but based on the original code I think we're good. If not, the OP can figure it out from here :) – ahuff44 Jun 02 '13 at 05:19
  • Please don't refer to `%` as the *modulus operator*; it is a *remainder operator*. A true modulus operator would be the addition operator for a ring over the integers, which this operator isn't. By using the correct name you help remind users of the unfortunate decision by K&R to treat negative numbers unusually. – Pieter Geerkens Jun 02 '13 at 05:33
  • What is the type of `Number` supposed to be? If it is an `int`, then the type of the expression `Number/12` is also of type `int`, and then there is no need to cast `Number/12` to `int` like you do. The operator `/` is _integer division_ in that case. – Jeppe Stig Nielsen Jun 02 '13 at 06:10