- Course
- Functions C
- Return value from Main
Return value from Main
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a new version of the program Main parameter calculator where you can return the following error codes from Main:
.
- Return 1 if the total parameters are different from 3.
- Return 2 if the second parameter is not a valid arithmetic sign (+, -, x, *, /).
- Return 3 if the first or third parameter is not a valid number.
- Return 0 if everything is correct.
Input
2 x 2
Output
4
Solution
using System;
public class MainParametersCalculator
{
public static int Main(string[] args)
{
if (args.Length != 3)
{
return 1;
}
int num1 = 1, num2 = 1;
try
{
num1 = Convert.ToInt32(args[0]);
num2 = Convert.ToInt32(args[2]);
}
catch
{
return 3;
}
char operation;
if (args[1] == "+" || args[1] == "-" || args[1] == "*" || args[1] == "/")
{
operation = Convert.ToChar(args[1]);
}
else
{
return 2;
}
switch (operation)
{
case '+':
Console.WriteLine(num1 + num2);
break;
case '-':
Console.WriteLine(num1 - num2);
break;
case '*':
Console.WriteLine(num1 * num2);
break;
case '/':
Console.WriteLine(num1 / num2);
break;
}
return 0;
}
}