I am working in a personalized Math class, I intend to implement basic operations methods so that they add, subtract, multiply or divide in a simple way without having to be calling the operators + - * / every time.
public class XMath
{
public static double Sum(params double[] values)
{
double result = 0;
if (values.Length < 1 || values is null) result = 0;
else if (values.Length == 1) result = values[0];
else foreach (double value in values) result += value;
return result;
}
public static double Subtract(params double[] values)
{
double result = 0;
if (values.Length < 1 || values is null) result = 0;
else if (values.Length == 1) result = values[0];
else foreach (double value in values) result -= value;
return result;
}
public static double Multiply(params double[] values)
{
double result = 0;
if (values.Length < 1 || values is null) result = 0;
else if (values.Length == 1) result = values[0];
else foreach (double value in values) result *= value;
return result;
}
public static double Divide(params double[] values)
{
double result = 0;
if (values.Length < 1 || values is null) result = 0;
else if (values.Length == 1) result = values[0];
else foreach (double value in values) result /= value;
return result;
}
}
My problem is that the Sum method works perfectly, but the others they throw wrong results
So, if += it works, because -=, *= and /= no
The main problem is that you initialize your
resultvariable with 0.Assume the array
double[] values = new [] { 1.0, 2.0, 3.0 }, yourSummethod computes0 + 1 + 2 + 3,Subtractcomputes0 - 1 - 2 - 3,Multiplycomputes0 * 1 * 2 * 3etc.The extra 0 makes no difference for the sum, but it affects the other operations.
You should initialize your operations with the first element of the array instead of 0.
You can also look into the Aggregate method which would simplify your code to