This program implements a calculator that performs mathematical operations using a stack-based approach. It processes mathematical expressions like addition, subtraction, multiplication, division, exponentiation, and factorials. The program utilizes a custom LinkedStack class to manage operations and follows standard operator precedence rules.
- Basic Arithmetic : Supports addition, subtraction, multiplication, division, and exponentiation.
- Factorial Calculation : Computes the factorial of integers.
- Parentheses Handling : Handles expressions with parentheses correctly.
- Constants : Supports constants like Euler's number (
e) and pi (p). - Operator Precedence : Correctly evaluates operations in the order of precedence using stacks.
-
fillStack():- Fills the stack with the individual elements of the input expression.
- Validates the expression and ensures that the operators and operands are in a valid sequence.
-
factorial(int n):- Computes the factorial of a given integer
n.
- Computes the factorial of a given integer
-
calcPowers():- Evaluates exponentiation (
^) operations.
- Evaluates exponentiation (
-
calcMulAndDiv():- Handles multiplication (
x) and division (/) operations.
- Handles multiplication (
-
calcPlusAndSub():- Handles addition (
+) and subtraction (-) operations.
- Handles addition (
-
calculate():- The main calculation function that processes the input expression and returns the result.
- It manages the entire sequence of operations by calling helper functions like
calcPowers,calcMulAndDiv, andcalcPlusAndSub.
- The calculator throws an exception if the input expression contains invalid characters or malformed operations. For example:
- Operators cannot be placed at the beginning or end of an expression.
- Invalid usage of factorial (
!) or mismatched parentheses will throw an exception.
- The input is a string containing the mathematical expression to be evaluated.
- Operators:
+,-,x,/,^,! - Constants:
efor Euler's number,pfor pi - Parentheses:
()for grouping - Example:
"3+5*(2^3)-6"
- The output will be the result of the expression after evaluation.
- The program requires a
LinkedStackclass that is used to manage the stack operations. Ensure this class is defined in your project.