我试图找出如何从参数数组中调用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();
}
答案 0 :(得分:5)
在循环中添加if语句,只添加值< 10
foreach (int val in vals)
{
if(val < 10)
{
sum += val;
}
}
答案 1 :(得分:3)
这是你想要做的吗?
static int SumVals(params int[] vals)
{
return vals.Where(i => i < 10).Sum();
}
答案 2 :(得分:2)
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();
}
答案 3 :(得分:1)
foreach (int val in vals) //for each integer value
{
if(val <10)
sum += val; //sum equals sum plus val. returns all values added together
}
答案 4 :(得分:1)
你可以使用LINQ来做到这一点:
static int SumVals(params int[] vals)//parameter array
{
return vals.Where(v => v < 10).Sum();
}
您必须将using System.Linq;
放在文件的顶部才能使其正常工作。
答案 5 :(得分:0)
怎么样:
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;
}
答案 6 :(得分:0)
static int SumVals(params int[] vals)//parameter array
{
return vals.Where(x => x < 10).Sum();
}