开发者

How to find nearest even number for given int? (given 11 return 12)

So how to create a function to return nearest up so nearest to 9 9+ 1 to given int leaving no 开发者_如何学Cremainder when divided by 2 int?


To round to the nearest int:

number+=(number & 1)


Round down to even

x & ~1

Round up to even

(x + 1) & ~1


"Nearest" is ambiguous when given an integer. Take, say, 9: both 8 and 10 are even, and are equally near to it. If you want to always go up, then something like...

int nearestEvenInt(int to)
{
  return (to % 2 == 0) ? to : (to + 1);
}


number % 2 == 0?number:number+1

Another way is (number>>1)<<1 but I'm not sure about negatives/little/big-endians.


The way I'd normally prefer is (number+1) & ~1, but not everyone recognises the idiom, so you might have to consider your audience.

In particular, if it's supposed to work for negative integers then non-two's-complement implementations of C and C++ don't recognise the idiom (it'll round odd negative numbers down instead of up on negative sign+magnitude numbers, and turn negative even numbers odd on ones' complement), so it's not entirely portable in the case where negative input is allowed.

The portable answer is (number % 2 == 0) ? number : number+1;, and let the compiler worry about optimization.

Beware also that you haven't defined what the result should be for INT_MAX, which is odd but for which there does not exist a larger even int value.


if (x %2 == 0) return x; else return x+1; ?


Since most of the answers here are either nonportable or have excess conditionals, here is the fast and portable answer:

number += (int)((unsigned)number & 1)

The case to unsigned ensures that bitwise-and is defined as expected, and the cast back to int (which is well-defined because both possible values of the bitwise and operation, zero or one, fit in int) prevents number from getting promoted to unsigned, which would then result in implementation-defined behavior when it's converted back to int to assign the result to number.


A little late to the party, but this is a clean solution

n += (n % 2);


I know the OP asked for int, but here's one answer for floats too:

number = Math.round(number * 0.5f) * 2; //Closest (up for middle)
number = Math.ceil(number * 0.5f) * 2; //Always Up
number = Math.floor(number * 0.5f) * 2; //Always Down
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜