i am trying to define a number "55.15 or something like that, i think this should be - double- am i right:)" wether even or not. i`m going to use that in a calculation and if it`s odd i`ll need to round it up to closest decimal value. if you please give me some suggestions i`ll be more than happy...
thanks...
Trying to define even/odd numbers please help
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.
AnttiRank #9,295 · 208 pointsPosted Jan 29, 2006, 8:51 AM EST
First round your float/double/decimal to nearest integer using Math.Round -method. Then you can calculate the 2-modulus of the integer. If modulus is 0, integer is even. If modulus is 1, integer is odd.
using System; using System.Collections.Generic; using System.Text; namespace EvenOdd { class Program { static void Main(string[] args) { double number = 55.15; int rounded = Convert.ToInt32(Math.Round(number)); Console.WriteLine(IsEven(rounded)); } static bool IsEven(int number) { bool isEven = false; int modulus = number % 2; if (modulus == 0) isEven = true; else if (modulus == 1) isEven = false; return isEven; } } }atilla4 pointsPosted Jan 30, 2006, 8:14 PM EST
thanks so much after little effort it worked.:))
AnttiRank #9,295 · 208 pointsPosted Jan 30, 2006, 11:26 PM EST
Just figured one (obvious) way to check if the int is even/odd. This is more efficient way, i think (for the computer, that is). This method is based on a simple fact, that all odd integers must end to bit 1, and all even numbers to the bit 0. For non-integer numbers, you still have to use the previous way, i think.
Some examples:
2 => '10'.
3 => '11'.
121 => '111 1001'
If we AND-mask the number 121 with 1 (that is ...0001), heres the result:
111 1001&&& &&&&
000 0001
=== ====
000 0001
And as we all recall, and operation simply checks if both of the operands are true(1). If both are true, the result is true. 1 AND 1 is true. 1 AND 0 is false etc...
using System; using System.Collections.Generic; using System.Text; namespace EvenOdd { class Program { static void Main(string[] args) { int number = -31; Console.WriteLine(number + ": " + IsEven(number)); number = 235578; Console.WriteLine(number + ": " + IsEven(number)); double number2 = 2332.1; Console.WriteLine(number2 + ": " + IsEven(number2)); number2 = -2332.0; Console.WriteLine(number2 + ": " + IsEven(number2)); } static bool IsEven(int number) { //this operation masks the number using bit mask 0x00000001 //if number's last bit is 1, the result of the bitwise-AND (&) operation is 1. //this result is converted to boolean and inverted using ! return !Convert.ToBoolean(number & 1); } static bool IsEven(double number) { bool isEven = false; double modulus = number % 2; if (modulus == 0) isEven = true; else if (modulus == 1) isEven = false; return isEven; } } }