简体   繁体   English

通过For循环添加数组偶数值。 C#

[英]Adding array even values through For-loop. C#

I am to establish an array and add only the even numbers in the array through a for-loop . 我要建立一个数组,并通过for-loop仅在数组中添加偶数。 I've established the array but unsure how to apply it in the loop. 我已经建立了数组,但是不确定如何在循环中应用它。 I think I have to use the % operator to only select the even numbers in the array. 我想我必须使用%运算符才能仅选择数组中的偶数。 I know how to set up a typical For-Loop but unclear how to use it with an array. 我知道如何设置典型的循环,但不清楚如何将其用于数组。 Any help works. 任何帮助都可以。

int[] bills = new int[5];

bills[0] = 131;
bills[1] = 121;
bills[2] = 2000;
bills[3] = 333;
bills[4] = 120;
bills[5] = 334;

Quick suggestion, use % (modulus) operator check for remainder like arrayvalue % 2 == 0 if condition true then it's even number else odd. 快速建议,使用% (模)运算符检查是否arrayvalue % 2 == 0数,如arrayvalue % 2 == 0如果条件为true则为偶数,否则为奇数。

foreach(int val in bills)
{
    if(val % 2 == 0)
    {
        //It's even number ... do your processing
    }
    else { continue; }
}

As a beginner, you could start using foreach loop to loop through each value. 作为初学者,您可以开始使用foreach循环遍历每个值。 To see the value is even or odd just apply modulus operator and check reminder is zero or not. 要查看该值是偶数还是奇数,只需应用模数运算符并检查提醒是否为零。

foreach(int bill in bills)
{
    if(bill%2 ==0)
    {
        //logic here
    }
}

Another approach, using Linq . 另一种方法,使用Linq

int[] onlyEventValues = bills.Where(x=> x%2==0).ToArray(); // filters and returns an array of even values.

Use foreach to loop all numbers you have 使用foreach循环显示所有数字
Use List<int> to save only even numbers 使用List<int>仅保存偶数

List<int> evenNumbers = new List<int>();
foreach(int val in bills)
{
    if(val % 2 == 0)
    {
        evenNumbers.Add(val);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM