仅从参数数组中调用某些值的和

本文关键字:调用 参数 数组 | 更新日期: 2023-09-27 18:04:01

我正试图找出如何从参数数组中调用10以下所有值的总和。

到目前为止,我已经弄清楚了如何调用一个值的值。我怎样才能/应该得到这个数字,有什么想法吗?
static int SumVals(params int[] vals)//parameter array
    {
        int sum = 0;
        foreach (int val in vals) //for each integer value 
        {
            sum += val; //sum equals sum plus val. returns all values added together
        }
        return sum;
    }
    static void Main(string[] args)
    {
        int sum = SumVals(100, 5, 2, 9, 800);
        Console.WriteLine("Summed Values = {0}", sum);
        Console.ReadKey();
    }

仅从参数数组中调用某些值的和

在循环中添加if语句,只添加值<10

foreach (int val in vals)
{
    if(val < 10)
    {
        sum += val;
    }
}

这就是你想要做的吗?

static int SumVals(params int[] vals)
{
    return vals.Where(i => i < 10).Sum();
}
static int SumVals(params int[] vals)//parameter array
    {
        int sum = 0;
        foreach (int val in vals) //for each integer value 
        {
            if(val < 10) //only add to the sum if value is less than 10
                 sum += val; //sum equals sum plus val. returns all values added together
        }
        return sum;
    }
    static void Main(string[] args)
    {
        int sum = SumVals(100, 5, 2, 9, 800);
        Console.WriteLine("Summed Values = {0}", sum);
        Console.ReadKey();
    }

您可以使用LINQ来完成:

static int SumVals(params int[] vals)//parameter array
{
    return vals.Where(v => v < 10).Sum();
}

你必须把using System.Linq;放在你的文件的顶部,使它工作

    foreach (int val in vals) //for each integer value 
    {
        if(val <10)
         sum += val; //sum equals sum plus val. returns all values added together
    }
static int SumVals(params int[] vals)//parameter array
{
     return vals.Where(x => x < 10).Sum();
}

如何:

static int SumVals(params int[] vals)//parameter array
    {
        int sum = 0;
        foreach (int val in vals) //for each integer value 
        {
            if (val >=10) continue;
            sum += val; //sum equals sum plus val. returns all values added together
        }
        return sum;
    }