43

试图确定我的整数列表是由奇数还是偶数组成,我想要的输出是一个真/假列表。我可以对列表 lst 执行以下操作还是需要创建一个循环?A 是输出。

    List <int> lst = new List <int>();
    A = IsOdd(lst);
4

5 回答 5

60

您可以尝试使用 Linq 来投影列表:

var output = lst.Select(x => x % 2 == 0).ToList();

这将返回一个新的 bool 列表,这些列表{1, 2, 3, 4, 5}将映射到{false, true, false, true, false}.

于 2013-09-15T23:55:32.237 回答
56

只需使用模数

遍历列表并在每个项目上运行以下命令

if(num % 2 == 0)
{
  //is even
}
else
{
  //is odd
}

或者,如果您想知道是否全部都是,您可以执行以下操作:

bool allAreEven = lst.All(x => x % 2 == 0);
于 2013-09-15T23:54:55.323 回答
22

至少有 7 种不同的方法可以测试一个数字是奇数还是偶数。但是,如果您通读这些基准,您会发现正如上面提到的 TGH,模运算是最快的:

if (x % 2 == 0)
               //even number
        else
               //odd number

以下是其他一些方法(来自网站):

//bitwise operation
if ((x & 1) == 0)
       //even number
else
      //odd number

//bit shifting
if (((x >> 1) << 1) == x)
       //even number
else
       //odd number

//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
       //even number
else
       //odd number
于 2014-08-04T00:32:37.190 回答
2
        #region even and odd numbers
        for (int x = 0; x <= 50; x = x + 2)
        {

            int y = 1;
            y = y + x;
            if (y < 50)
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
                Console.ReadKey();
            }

        }

        //order by desc

        for (int z = 50; z >= 0; z = z - 2)
        {
            int w = z;
            w = w - 1;
            if (w > 0)
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
                Console.ReadKey();
            }
        }
于 2017-07-24T15:18:55.857 回答
-1

--简单的代码--

        #region odd / even numbers  order by desc

        //declaration of integer
        int TotalCount = 50;
        int loop;

        Console.WriteLine("\n---------Odd Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 == 0)
            {
                Console.WriteLine("Even numbers : #{0}", loop);
            }
        }

        Console.WriteLine("\n---------Even Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 != 0)
            {
                Console.WriteLine("odd numbers : #{0}", loop);
            }
        }

        Console.ReadLine();

        #endregion
于 2018-04-19T02:00:49.970 回答