Exercise
Function Calculator, Params Of Main
Objective
Write a C# program to calculate a sum, subtraction, product or division, analyzing the command line parameters:
calc 5 + 379
(Parameters must be a number, a sign, and another number; allowed signs are + - * x / )
Write Your C# Exercise
C# Exercise Example
// 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}");
}
}
}