Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / algorithm

How To Implement a Scientific Calculator in C++

4.63/5 (21 votes)
21 Jan 2014CPOL7 min read 88.2K   1.7K  
A brief overview on mathematical implementations with programming language

Table of Contents

  1. Abstract
  2. Introduction
  3. Mathematical problems coding
    1. Inputs wide possibilities
    2. The input formulas should match standard rules of math
    3. Length of input formula
  4. Implementation overview
    1. Data class
    2. MyChecker class
    3. MyFixer class
    4. Calculator class
  5. User guide
  6. Appendix
    1. Linked lists
  7. Conclusion

1. Abstract

Have you ever tried to put the upper formula in one of your programs, but you found it hard to be calculated? Have you ever stopped writing one of your programs because you need to use complex formulas and there isn't a way to calculate them in your programming language? Have you gone to use programming languages such as FORTAN or MATLAB, because you need to use some of their mathematical power, although at the same time if you have this power in your main language you may produce a better program?

If you are one of those, then this article may be good for you as it gives you two solutions to your problem; one is how to write mathematics programs, and the other is a header file in C++ that you can use to calculate formulas like that in Fig.1, in order to facilitate your creative C++ programs.

2. Introduction

Mathematical programming, together with subordinate programming languages, is the backbone of any programming language and one of the most important reasons to use computers. That is because nearly all sciences in the world is dependent on mathematics. Then, the need to easier methods to do mathematics continues to be one of the most required things nowadays and will still be obtainable until the end of the world. So, from this point, we are working to implement a scientific calculator written by me, and shall be written by you in the next days, unless you don't want to do so.

In C++, there are some libraries that function on mathematics such as math.h and c math, but these libraries don't give you all the operations you need, however, they are the basis which we build our implementation on.

3. Mathematical Problems coding

While writing mathematics programs, you will experience some problems which all programmers have experienced before. I put these problems in your hand in order to pay attention. You may not look at this as a problem as the word means, but I write the problem that has caused me some difficulty during coding.

3.1. Inputs Wide Possibilities

The first problem which you may experience is the inputs wide possibilities. You don't know what the user will give you as input, so you should first determine what kind of math your program will deal with, and make sure that your user won't enter anything outside it especially if you receive the inputs as a string or a stream, or you receive it by a console interface. So to handle this problem, you should first check the inputs and then do your operations progressively on the input, for example:

  • would your program handle formulas with simple operators (+,-,/,*) only?
  • or your program will go up until intersection operators with brackets?
  • or your program will go up until trigonometric functions (sin, cos, . . . )?
  • and as you go, you should first determine the field you will depend on and then start.

3.2. The Input Formulas Match the Standard Rules of Math

The second problem which you may experience is that the user may enter input formulas with some abbreviation, such as 2x which means 2*x or 2(sin(45)) which means 2*sin(45) or 2++++++x , whereas your program is designed to treat with one operator only, etc.

So you should first edit the input formula until it is appropriate for your program and then send it to your functions.

3.3. Length of Input Formula

The third problem you may have is the input length, since the user may enter short or long formulas. In this case, you have two solutions: the first is using a long array which can read any length of input formula, but it's a bad solution in my opinion because it will waste memory if the user enters a small formula. The best solution in my opinion is using counters which depend on linked lists (see the appendix) as it allocates memory as you need only, and so you won't allocate memory more than your requirement. In this case, I use vectors.

4. Overview of the Implementation

4.1. Data Class

Data class is the container class of my implementation. In this class, I put the main libraries which I need in the program and the public method which I will use as assistant functions as:

  1. double charVtod (vector<char>ch) function converts a double number form the input formula to a double number
  2. double getNum (vector<char> &form, int &orderm, int &digit); read a number form the input formula
  3. unsigned getDigits(long num); count the digits of a long number
  4. vector<char> dtoVchar (double num); convert double numbers to a vector of characters
Java
 class Data  
{
protected:
	int temp;          //temperature variable
	char tempChar;     //temperature char
	
	bool hasVar;       //checking for variables	 
	double charVtod (vector<char>ch); //convert from vector of character to double
	//reading a number from vector and return its digit's count int digit by reference
	double getNum (vector<char> &form, int &orderm, int &digit);
	unsigned getDigits(long num); //return the digits number of a long num

	//convert double to vector
	vector<char> dtoVchar (double num);
};//end data

4.2. MyChecker Class

MyChecker class is a class which is used for checking the input formula and the agreement of it to my program mathematical cover as if the user enters a wrong formula; this class should alert him about that, wrong entry as such as:

x**x ,si(45), /52312, etc...

About functions:

  1. inline bool isOp(char &ch); is used for checking for normal operators +, -, *, /
  2. b-bool isVar(vector<char>vars,char &ch); is used for checking for variables
  3. bool _check (vector<char> &ch, vector<char>vars); is the function which uses other class function in order to check the entry formula
  4. bool isTriangle (vector<char> &ch , int &temp); is the function which is used for checking for trigonometric functions.
  5. bool editSigns (vector<char> &ch); is the function which is used to edit signs as ++ becomes + and -+ becomes -, etc.
  6. bool check(vector<char>form, char mainVar ); is the function which is used to check entry formula with one variable, read by the other argument mainVar, such as 2x + 2 and mainVar = 'x'
  7. bool check(vector<char>form, vector<char>vars); is the function which is used to check entry formula with more than one variables read by the vector vars such as 2x+3y
Java
class MyChecker : public Data 
{
private:
	inline bool isOp(char &ch);
	bool isVar(vector<char>vars,char &ch);
	//check trigonometric functions
	bool _check (vector<char> &ch, vector<char>vars);  //checker function
protected:
	bool isTriangle (vector<char> &ch , int &temp);
	bool editSigns (vector<char> &ch);
	bool check(vector<char>form, char mainVar );  //check with formulas
	bool check(vector<char>form, vector<char>vars); };//check with formulas and variables 

4.3. MyFixer Class

MyFixer class is the class which its minor is to edit formulas in order to make formula adaptable to my program and the next class calculator, for example: if the input is xx put * between them and the result become x*x; this function has only two functions; one of them is invoking the other:

  1. void fix(vector<char> &ch); This function is invoked by other son classes and receives the formula and sends it to the other function.
  2. void _fix (vector<char> &ch); This function in invoked by the classes' function and does the required editing.
Java
class MyFixer : public MyChecker
{
protected:

	void fix(vector<char> &ch);

private: 
	int temp;
	void _fix  (vector<char> &ch);
	

};//end MyFixerer

4.4. Calculator Class

Calculator class is the backbone of this program, this class's functions are the functions which give the calculation of a formula; with discovering its functions:

firstRank, secondRank and thirdRank are functions which divide formula to three phases:

The first related to power and trigonometric functions, the second is for * and / operations and the third is for + and - operations, with putting on consider the function getBorder is using for determining the brackets which calculation is done within and then delete it.

This class has 6 overloading of the function calc for working with the three cases which take characters vector, arrays and strings; the functions _calc at final is the function which takes the formula from the six overloading functions and then do calculation.

Java
class Calculator : public MyFixer
{
private:
	int str, end, // sub calculation borders 
	              //depending on brackets
		digit,digit1,digit2,    //get number digit
		temp, temp1;     //temperature variable

	vector<char> charNum;
	double num, num1, num2; //storing double number	bool final;      //final time do mathematics
	
	double getCaclNum (vector<char> &form, int &order, int &count);
	void getBorder (vector<char> &form);
	void firstRank (vector<char> &form); //trigonometric and power
	void secondRank (vector<char> &form); //do multiplying and division
	void thirdRank (vector<char> &form); //summing and subtracting
	vector<char> _calc (vector<char> formula);
	vector<char> strToVector (string form);
	vector<char> charToVector(char form [] );
public:

	Calculator () :final(false){}	
	double calc (vector<char> formula);
	double calc(char formula []);
	double calc(string formula );
	double calc (vector<char> formula, char var, double varValue);
	double calc (char formula [], char var, double varValue);
	double calc (string formula , char var, double varValue);
	
};//end calculator

5. User Guide

Now we have the part of how to use these classes:

  1. First, you need to include these classes in your program
  2. Make including in your cpp file for calculator.h file
  3. Make an object from calculator class
  4. Use one of the six overloading calc functions

For example, if you want to get a function from the user with one variable, then get the variable's value and print the result, the code will be as follows:

C++
#include "Calculator.h"
#include <string>

using namespace std;

void main ()
{
	Calculator c1;  //object of Calculator
	string form;    //reading formula in
	char var;       //reading variable
	double value;   //reading variable value
		while(true)
		{
		cout<<"Please, enter your formula:";cin>>form;
		cout<<"enter your variable:";cin>>var;
		cout<<"Enter "<<var<<" value:";cin>>value;
		cout<<"result = "<<c1.calc(form, var, value)<<endl;
		getche();
		system("cls");
		}
	}//end main 

And the result will be as in fig 2:

and later, you can use it in more complex programs.

6. Appendix

6.1. Linked List

In computer science, a linked list1 is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a datum and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence.

7. Conclusion

This article is to give you the lines on how to program a scientific calculators, but there isn't everything. This field is so wide and there is a lot of research on it, but I wish this article will help you to start.

Best wishes! Smile | :)

8. Reference

  1. http://en.wikipedia.org/wiki/Linked_list

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)