3
Program Summary
Good morning, I’m developing a calculator that asks the user for the amount of numbers that will be calculated, the operation and the numbers in question. To store the values, I use a array. The code that calculates the numbers of the array is:
The Code
for (i = 0; i < arrayLength; i++) { result /= num[i]; }
Where arrayLength is the size of the array, and "result" is a variable of type double declared at 0.
Problem
*Assuming we have one array one-dimensional with 2 positions whose values are one[0] = 120 and one[1] = 5*
The problem is that when the division is executed, what is eventually calculated is: (0 / 120) / 5
Completion
I’d like to know how to go through mine array "in a" and divide the values contained in it efficiently. And if possible a way to reduce the code size.
Complete 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));
}
The same problem happens for multiplication, which cannot start at 0. It would be better to put the
result
as the first element of the array and do the calculations forward. Note: Watch the Length Writing ErrorarrayLenght
which is quite common, although it does not affect the program itself.– Isac
@Isac Thanks for the grammar correction. Could fix my source code for better viewing?
– Stacklysm