Junior
From PDF
Coding
C# Coding Interview
Basic Calculator (Add, Subtract, Multiply, Divide)?
double Calculate(double a, double b, char op)
{
return op switch
{
'+' => a + b,
Follow on:
'-' => a - b,
'*' => a * b,
'/' => b != 0 ? a / b : throw new DivideByZeroException(),
_ => throw new ArgumentException("Invalid operator"),
};
}
Explanation:
Simple switch statement performing basic arithmetic, with divide-by-zero check.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png