Ejercicio
Función Calculadora, Parámetros De Main
Objectivo
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 / )
Ejemplo Ejercicio C#
Mostrar Código C#
// 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}");
}
}
}
Salida
-- Case 1: Execution with incorrect number of arguments
dotnet run
Error: Please provide two numbers and an operator.
-- Case 2: Execution with addition operation
dotnet run 5 + 3
Result: 8
-- Case 3: Execution with subtraction operation
dotnet run 10 - 4
Result: 6
-- Case 4: Execution with multiplication operation using '*' symbol
dotnet run 6 * 7
Result: 42
-- Case 5: Execution with multiplication operation using 'x' symbol
dotnet run 6 x 7
Result: 42
-- Case 6: Execution with division operation
dotnet run 8 / 2
Result: 4
-- Case 7: Execution with division by zero
dotnet run 10 / 0
Error: Cannot divide by zero.
-- Case 8: Execution with invalid operator
dotnet run 5 & 3
Error: Invalid operator. Use +, -, *, x, or /.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp