Program Summary
Good morning, I'm developing a calculator that asks the user for the number of numbers that will be calculated, the operation and the numbers in question. To save the values, I use an array . The code that calculates the array numbers is:
The Code
for (i = 0; i < arrayLength; i++) { result /= num[i]; }
Where arrayLength is the size of array , and "result" is a double variable declared with a value of 0.
Problem
Assuming we have a one-dimensional array with 2 positions whose values are in a [0] = 120 and a [1] = 5 *The problem is that when the division is executed, what ends up being calculated is: (0/120) / 5
Conclusion
I would like to know how to go through my array "num" and divide the values contained in it in an efficient way. And if possible a way to reduce code size.
Full Code
static void Main(string[] args)
{
int arrayLength, loopCounter = 0;
int numCounter = 1;
int i = 0;
double result = 0;
string operation = "";
Console.WriteLine("Digite a quantidade de números a serem calculados");
arrayLength = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nEscolha a operação:\n\n1: Soma\n2: Subtração\n3: Multiplicação\n4: Divisão (Temp. Desativado)\n");
operation = Console.ReadLine();
Console.WriteLine("");
double[] num = new double[arrayLength];
while (loopCounter < arrayLength)
{
Console.Write("Digite o {0}º valor: ", numCounter);
num[loopCounter] = Convert.ToDouble(Console.ReadLine());
numCounter++;
loopCounter++;
}
switch (operation.ToUpper())
{
case "1":
for (i = 0; i < arrayLength; i++)
{
result += num[i];
}
break;
case "2":
for ( i = 0; i < arrayLength; i++)
{
result -= num[i];
}
break;
case "3":
result = 1;
for (i = 0; i < arrayLength; i++)
{
result *= num[i];
}
break;
case "4":
for (i = 0; i < arrayLength; i++)
{
result /= num[i];
}
break;
default:
Console.WriteLine("Operação Inválida.");
break;
}
Console.Write("\nO resultado é: ");
Console.WriteLine(Math.Round(result,2));
}