Hello,
I want to write a calculator.
This calculator should have 2 dynamic storages which store as much storage as the user wants to type.
How do I implement such dynamic storages?
/* A calculator that handles any amount of operations
* does no input error checking
* the result of divide by zero is zero
*
* example input
* 1 + 3 / 3 * 6 - 1
* result 7
*/
#include <iostream>
// performs arithmetic based on two operands and one operator
double do_operation(constdouble, constdouble, constchar);
int main(void)
{
// variables
double left = 0; // stores the left hand side of operation
double right = 0; // stores the right hand side of operation
double total = 0; // stores the total
char operation = 0; // stores the operator ( a c++ keyword )
// give a nice welcome
std::cout << "Please enter the opertion\n: ";
// if "n" is a number and "o" is an operator, the expected input is
// n o n o n ... o n
// ( a number followed by a series of operator-number pairs )
// read the left number first
std::cin >> left;
// keep reading until the user hits enter
while (std::cin.peek() != '\n')
{
// read the operator-number pair
std::cin >> operation >> right;
// calculate the result
total = do_operation(left, right, operation);
// the total becomes the left hand number
// in case there is another operator-number pair
left = total;
}
// print result
std::cout << "The total is: " << total << std::endl;
return 0;
}
// do the arithmetic
double do_operation(constdouble left, constdouble right, constchar operation)
{
double result = 0;
switch(operation)
{
case'+': result = left + right; break;
case'-': result = left - right; break;
case'*': result = left * right; break;
case'/': result = right != 0 ? left / right : 0; break;
// add more operations as wanted
default : std::cout << "unexpected operand\n";
}
return result;
}