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();
}
Another question is, how can I return the average of these int values?
This question is related to
c#
You have tried the wrong variable, ints
is not the correct name of the argument.
public int Sum(params int[] customerssalary)
{
return customerssalary.Sum();
}
public double Avg(params int[] customerssalary)
{
return customerssalary.Average();
}
But do you think that these methods are really needed?
Though the answers above all are different flavors of correct, I'd like to offer the following solution, which includes a null check:
decimal sum = (customerssalary == null) ? 0 : customerssalary.Sum();
decimal avg = (customerssalary == null) ? 0 : customerssalary.Average();
If you are using visual studio 2005 then
public void sumAverageElements(int[] arr)
{
int size =arr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
}
average = sum / size; // sum divided by total elements in array
Console.WriteLine("The Sum Of Array Elements Is : " + sum);
Console.WriteLine("The Average Of Array Elements Is : " + average);
}
customerssalary.Average();
customerssalary.Sum();
i refer so many results and modified my code its working
foreach (var rate in rateing)
{
sum += Convert.ToInt32(rate.Rate);
}
if(rateing.Count()!= 0)
{
float avg = (float)sum / (float)rateing.Count();
saloonusers.Rate = avg;
}
else
{
saloonusers.Rate = (float)0.0;
}
Using ints.sum()
has two problems:
customerssalary
, not ints
Sum()
, not sum()
.Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average()
which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double
:
double average = ((double) sum) / customerssalary.Length;
Source: Stackoverflow.com