Exercise
Function Calculator, Params And Return Value 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 / )
This version must return the following error codes:
1 if the number of parameters is not 3
2 if the second parameter is not an accepted sign
3 if the first or third parameter is not a valid number
0 otherwise
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 int Main(string[] args)
{
// Check if the correct number of arguments (3) are passed
if (args.Length != 3)
{
// Return error code 1 if the number of parameters is incorrect
Console.WriteLine("Error: Please provide two numbers and an operator.");
return 1;
}
// Try to parse the first number from the command line arguments
double num1;
if (!double.TryParse(args[0], out num1))
{
// Return error code 3 if the first parameter is not a valid number
Console.WriteLine("Error: The first parameter is not a valid number.");
return 3;
}
// Try to parse the second number from the command line arguments
double num2;
if (!double.TryParse(args[2], out num2))
{
// Return error code 3 if the third parameter is not a valid number
Console.WriteLine("Error: The third parameter is not a valid number.");
return 3;
}
// Get the operator from the second parameter
string operatorSign = args[1];
// 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; // Perform addition
break;
case "-":
result = num1 - num2; // Perform subtraction
break;
case "*":
case "x": // Allow 'x' as multiplication sign
result = num1 * num2; // Perform multiplication
break;
case "/":
if (num2 == 0)
{
// Handle division by zero
Console.WriteLine("Error: Cannot divide by zero.");
validOperation = false;
}
else
{
result = num1 / num2; // Perform division
}
break;
default:
// Return error code 2 if the operator is invalid
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}");
return 0; // Return 0 to indicate successful operation
}
// Return an error code if the operation was not valid
return 2; // Return error code 2 if the operator is invalid
}
}