Simple C++ Calculator
Posted by Samath
Last Updated: January 05, 2017

This is a simple calculator using templated functions in c++. This program have the basic operation of a calulator (+,-,* and /). the main aim of this program is to demonstrate templated functions.

#include <iostream>

using namespace std;
template<class type1, class type2> double add(type1 num1, type2 num2)
{
  return num1+num2;
}

template<class type1, class type2> double subtract(type1 num1, type2 num2)
{
  return num1+num2;
}

template<class type1, class type2> double divide(type1 num1, type2 num2)
{
  return num1/num2;
}

template<class type1, class type2> double multiply(type1 num1, type2 num2)
{
  return num1*num2;
}
int main()
{  
    
    double num1, num2;
    char op;
    cout << "Please enter first number: ";
    cin >> num1;
    cout << "Enter Operator [+,-,*,/] : ";
    cin >> op;
    cin.ignore();
    cin.clear();
    cout << "Please enter second number: ";
    cin >> num2;
    int result;
    if(op == '+'){result = add(num1, num2);}
    else if(op == '-'){result = subtract(num1, num2);}
    else if(op == '*'){result = multiply(num1, num2);}
    else{result = divide(num1, num2);}
    
    cout << "Result: " << result << endl;
  
  return 0;
}

 

Related Content
Simple Calculator using C#
Simple Calculator using C#
Samath | Dec 30, 2020
Calculator Program in Java
Calculator Program in Java
Samath | Jan 07, 2021
Simple Calculator using Python
Simple Calculator using Python
Samath | Jan 09, 2017
GPA Calculator using C#
GPA Calculator using C#
Samath | Jan 01, 2021
Simple GPA calculator in Java
Simple GPA calculator in Java
Samath | Jan 17, 2024
GPA Calculator in C++
GPA Calculator in C++
Samath | Jan 17, 2024
GPA Calculator using Python
GPA Calculator using Python
Samath | Jan 20, 2024
Scientific Calculator using C#
Scientific Calculator using C#
Samath | Jan 08, 2021