Ejercicio
Función calculadora, parámetros de Main
Objetivo
Crear un programa en C# para calcular una suma, resta, producto o división, analizando los parámetros de la línea de comandos:
calc 5 + 379
(Los parámetros deben ser un número, un signo y otro número; los signos permitidos son + - * x / )
Código de Ejemplo
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Main method to drive the program
public static void Main(string[] args)
{
// Check if the correct number of arguments (3) are passed
if (args.Length != 3)
{
Console.WriteLine("Error: Please provide two numbers and an operator.");
return;
}
// Parse the first number and operator from the command line arguments
double num1 = double.Parse(args[0]);
string operatorSign = args[1];
double num2 = double.Parse(args[2]);
// Perform the calculation based on the operator
double result = 0;
bool validOperation = true;
// Switch statement to handle different operations
switch (operatorSign)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
case "x": // Allow 'x' as multiplication sign
result = num1 * num2;
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Error: Cannot divide by zero.");
validOperation = false;
}
else
{
result = num1 / num2;
}
break;
default:
Console.WriteLine("Error: Invalid operator. Use +, -, *, x, or /.");
validOperation = false;
break;
}
// Output the result if the operation is valid
if (validOperation)
{
Console.WriteLine($"Result: {result}");
}
}
}