A C++ command-line calculator capable of evaluating complex mathematical expressions, managing variables, and defining custom functions. This tool leverages an efficient token-based parsing system based upon the shunting-yard algorithm for accurate numerical calculations.
This project requires C++17 or above for features like std::optional and std::string_view.
g++ -std=c++17 -I include src/*.cpp -o calscriptRun the executable to start the calculator.
Built-in mathematical constants:
pi- Pi (3.14159...)e- Euler's number (2.71828...)phi- Golden ratio (1.61803...)sqrt2- Square root of 2 (1.41421...)ans- Result of the last calculation
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
In order of precedence:
!- Factorial^- Exponentiation*,/,%- Multiplication, Division, Modulo+,-- Addition, Subtraction
The parser intelligently recognizes:
2(3)evaluates to64pievaluates to4 * pi2sin(30)evaluates to2 * sin(30)(2+3)(4+5)evaluates to(2+3) * (4+5)
def [variable_name] [expression]
Example:
def radius 5
def area pi*radius^2
upd [variable_name] [expression]
Example:
upd radius 10
upd area pi*radius^2
create func [name]([param1], [param2], ...): [expression]
Example:
create func area(r): pi*r^2
create func hypotenuse(a, b): sqrt(a^2 + b^2)
Functions can be called directly:
area(5)
hypotenuse(3, 4)
ls vars- Display all defined variablesls hist- Show calculation historyls funcs- List all defined functions
del [variable_name]- Delete a specific variabledel func [function_name]- Delete a functiondel vars- Delete all variablesdel hist- Clear calculation history
exit- Close the calculatorclear- Clear the screen
2 + 3 * 4 # Returns 14
(2 + 3) * 4 # Returns 20
sin(30) # Returns 0.5
log(100) # Returns 2
def radius 5
pi * radius^2 # Calculate circle area = 78.54
def area ans # Save result to variable
create func circle_area(r): pi*r^2
circle_area(5) # Returns 78.54
create func quad(a, b, c, x): a*x^2 + b*x + c
quad(1, -3, 2, 2) # Returns 0
create func normal_pdf(x, mean, std): (1/(std*sqrt(2*pi)))*e^(-0.5*((x-mean)/std)^2)
normal_pdf(0, 0, 1) # Returns 0.3989 (standard normal at peak)
- No control structures (if/else, loops)
- No array/list support
- Limited symbolic manipulation capabilities
- Simple text-based interface
- Use parentheses to clarify operator precedence in complex expressions
- Always use parentheses with function calls for clarity
- Use descriptive variable and function names
- Break complex calculations into smaller parts using intermediate variables
The calculator provides error messages for:
- Syntax errors
- Undefined variables/functions
- Division by zero
- Invalid function arguments
- Mismatched parentheses