Thursday, March 7, 2024

My Simple Calculator Using OOP in C++

 A simple calculator program that I wrote using object-oriented programming using C++ programming language.




Program Listing

#include <iostream>


class Calculator {

public:

    double add(double a, double b) {

        return a + b;

    }


    double subtract(double a, double b) {

        return a - b;

    }


    double multiply(double a, double b) {

        return a * b;

    }


    double divide(double a, double b) {

        if (b != 0) {

            return a / b;

        } else {

            std::cout << "Error: Division by zero is not allowed." << std::endl;

            return 0.0;

        }

    }

};


int main() {

    double num1, num2;

    char operation;


    std::cout << "\tMy Simple Calculator Using OOP in  C++\n\n";

    std::cout << "\tEnter two numbers: ";

    std::cin >> num1 >> num2;


    std::cout << "\tEnter select an operator (+, -, *, /): ";

    std::cin >> operation;


    Calculator calc;


    double result;


    switch (operation) {

        case '+':

            result = calc.add(num1, num2);

            break;

        case '-':

            result = calc.subtract(num1, num2);

            break;

        case '*':

            result = calc.multiply(num1, num2);

            break;

        case '/':

            result = calc.divide(num1, num2);

            break;

        default:

            std::cout << "I\tnvalid operator." << std::endl;

            return 1;

    }


    std::cout << "\n\tThe Result is " << result << "." <<std::endl;

    std::cout << "\n\n\tEnd of Program\n";

    return 0;

}


No comments:

Post a Comment