Gather Requirements
A simple calculator provides the following basic functionality:
- Addition of two numbers,
- Subtraction of two numbers,
- Multiplication of two numbers and
- Division of two numbers.
- Reset
- Exit
- Check for Division By Zero
Implementation Decisions
- Switch statement for Choice between the Functions
- Basic I/O (Input stream for user input, Output stream for result to display)
- Expressions (Arithmetic Operators, Assignment Operator )
- Choice of Correct Data Types
Program Snippet
#include
#include
using namespace std;
double Add(double n1, double n2){
double r = n1 + n2;
return r;
}
double Sub(double n1, double n2){
double r = n1 - n2;
return r;
}
double Mul(double n1, double n2){
double r = n1 * n2;
return r;
}
double Div(double n1, double n2){
double r;
if(n2==0)
r = 0;
else
r = n1/n2;
return r;
}
int main(){
double n1, n2;
char choice;
bool flag = false;
double r;
do{
cout<<"\n\n\t\tBASIC CALCULATOR\n";
cout<<"\t\t----------------\n";
cout<<"\t\t(+)Add\n";
cout<<"\t\t(-)Subtract\n";
cout<<"\t\t(*)Multiply\n";
cout<<"\t\t(/)Divide\n";
cout<<"\t\t(#)Reset\n";
cout<<"\t\t(^)Exit\n";
cout<<"\t\t-----------------\n";
cout<<"\n\nEnter First Number: ";
cin>>n1;
cout<<"\n\nEnter Second Number: ";
cin>>n2;
cout<<"\n\nOperation?";
cin>>choice;
switch(choice){
case '+':
r = Add(n1,n2);
cout<<"\n\nReuslt of Addition:"<
break;
case '-':
r = Sub(n1,n2);
cout<<"\n\nReuslt of Subtraction:"<
break;
case '*':
r = Mul(n1,n2);
cout<<"\n\nReuslt of Multiplication:"<
break;
case '/':
r = Div(n1,n2);
if(r==0)
cout<<"\n\nDivision by Zero not Possible\n";
else
cout<<"\n\nReuslt of Division:"<
break;
case '#':
flag = false;
break;
case '^':
flag=true;
break;
default:
cout<<"\n\nFunction Does not Exist\n";
break;
}
}
while(flag!=true);
return 0;
system("pause");
}
Program Explanation
The program starts at the "main()" method. First, the input numbers to the calculator programs have been declared. Since, the user might enter a number of any possible range, a double datatype would be preferable over a float. For a detailed review of data types and choice of one data type over another, please Click Here!
For better organization and future modifications to the functionality of the calculator, separate methods have been created for all operations. The expressions in each method consist of arithmetic ( +, - , *, / ) and assignment (=) operator.
The main program functionality sits inside a do-while loop which exists upon selection of the "Exit" menu from the Calculator menu. A flag parameter checks for when to exit and till when to stay in the loop.
Summary
A Simple/Basic calculator implementation involves methods for the basic arithmetic operations and means to choose the operation to be applied on the two numbers input by the user. A do-while loop keeps going back to the calculator menu until "Exit". A switch statement serves to implement the operation selection.
0 comments:
Post a Comment