我如何返回int数组的总和 [英] how can i return the sum , average of an int array

查看:73
本文介绍了我如何返回int数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义两种返回int数组
sum 平均值的方法。方法定义如下:-

I need to define two methods for returning the sum and average of an int array the method defining is as follow:-

public int Sum(params int[] customerssalary)
{

         // I tried the following but it fails   return customerssalary.sum();
}

另一个问题是如何返回这些int值的平均值? / p>

Another question is how can I return the average of these int values ?.

推荐答案

这是您应该这样做的方式,我这样说是因为您显然是C#的新手,应该尝试理解一些基本的东西是如何工作的!

This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!

public int Sum(params int[] customerssalary)
{
   int result = 0;

   for(int i = 0; i < customerssalary.Length; i++)
   {
      result += customerssalary[i];
   }

   return result;
}

具有此 Sum 函数,您也可以使用此函数来计算平均值...

with this Sum function, you can use this to calculate the average too...

public decimal Average(params int[] customerssalary)
{
   int sum = Sum(customerssalary);
   decimal result = (decimal)sum / customerssalary.Length;
   return result;
}

使用十进制键入第二个函数是因为除法可以轻松返回非整数结果

the reason for using a decimal type in the second function is because the division can easily return a non-integer result

其他人提供了Linq替代方案是我无论如何都会用到的东西,但是有了Linq,反正拥有自己的功能毫无意义。我假设您被要求执行这样的功能,以证明您对C#的理解,但是我可能是错的。

Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.

这篇关于我如何返回int数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆