A C++ command-line calculator that leverages the shunting-yard algorithm for evaluating complex mathematical expressions, featuring variable storage and command history.
This project requires C++17 or above due to the use of features like std::optional
and std::string_view
.
To compile the project, use:
g++ -std=c++17 -I include src/*.cpp
The -std=c++17
flag is required to enable C++17 features. Run the resulting executable to start the calculator.
The following mathematical constants are built-in:
pi
- Pi (3.14159...)e
- Euler's number (2.71828...)phi
- Golden ratio (1.61803...)sqrt2
- Square root of 2 (1.41421...)
All functions require brackets for proper parsing:
sin(x)
- Sine (in degrees)cos(x)
- Cosine (in degrees)tan(x)
- Tangent (in degrees)log(x)
- Base-10 logarithmln(x)
- Natural logarithmsqrt(x)
- Square root
Supported mathematical operators in order of precedence:
!
- Factorial^
- Exponentiation*
,/
,%
- Multiplication, Division, Modulo+
,-
- Addition, Subtraction
The parser supports implicit multiplication in various forms:
-(2)
evaluates to-2
(2)(3)
evaluates to6
4(2-3)
evaluates to-4
(2-3)4
similarly evaluates to-4
def [variable_name] [value]
Example:
def x 10
x + 5 # Evaluates to 15
upd [variable_name] [value]
Example:
upd x ans # Updates x to the last calculated result
ls vars
- Display all defined variablesls hist
- Show calculation history
del [variable_name]
- Delete a specific variabledel vars
- Delete all variablesdel hist
- Clear calculation history
exit
- Close the calculator
-
Trigonometric calculations are performed in degrees. Using radian values directly will not provide expected results.
-
Function calls can work without brackets for single numbers or variables, but brackets are recommended for clarity and required for expressions:
sin(60) # Correct, recommended sin 60 # Works for single numbers 8(sin 30) # Works, evaluates to 4 sin 60/2 # Evaluates as (sin 60)/2 = 0.433, not sin(60/2) sin(60/2) # Use brackets for expressions
-
The special variable
ans
always contains the result of the last calculation.
# Basic arithmetic
2 + 3 * 4 # Returns 14
# Using functions
sin(30) # Returns 0.5
log(100) # Returns 2
# Variable operations
def radius 5
pi * radius ^ 2 # Calculate area
def area ans # saves computed value to area
ls vars # Shows radius & area variables
# Updating variables
upd radius 10 # Updates radius
pi * radius ^ 2 #find new area
upd area ans #area takes new value
# Implicit multiplication
2(3+4) # Returns 14
The parser includes error handling for:
- Invalid syntax
- Undefined variables
- Division by zero
- Invalid function arguments
- Malformed expressions
If an error occurs, an appropriate error message will be displayed, and the calculator will continue running.
Working on more features and a better GUI. If you have recommendations, pm me, add issue or fork this and add your idea.