Object Oriented Programming C++ Simple Calculator
This is a beginner C++ OOP program.
#include <iostream> #include <limits> #include <math.h> #include <cmath> // for log function using namespace std; 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){ if(a==0 && b==0){ cout<<"Error! Invalid operation!"<<endl; return std::numeric_limits<double>::quiet_NaN(); } return a*b; } double divide(double a, double b){ if(b==0) { cout<<"Error! Cannot divide by 0!"<<endl; return std::numeric_limits<double>::quiet_NaN(); } return a/b; } double power(double a, double b){ return pow(a,b); } double loggy(double a) { //can't be 0 or less return log(a); } double factorial(double a){ if(a==1 || a==0) return 1; else return a*factorial(a-1); } }; int main() { calculator k; double a,b; double rez; int f, i=1; while(i!=0){ cout << "Choose function you want to use " << endl; cout << "1 - Addition " << endl; cout << "2 - Subtraction " << endl; cout << "3 - Multiplication " << endl; cout << "4 - Division " << endl; cout << "5 - a^b"<<endl; cout << "6 - Compute the log"<<endl; cout << "7 - Compute factorial"<<endl; cout << "Input: " << endl; cin >> f; cout << endl; switch(f){ case 1: //Addition cout << "a= "; cin >> a; cout << "b= "; cin >> b; cout << a << " + " << b << " = "; cout << k.add(a, b); break; case 2: //Subtraction cout << "a= "; cin >> a; cout << "b= "; cin >> b; cout << a << " - " << b << " = "; cout << k.subtract(a, b); break; case 3: //Multiplication cout << "a= "; cin >> a; cout << "b= "; cin >> b; cout << a << " x " << b << " = "; cout << k.multiply(a, b); break; case 4: //Division cout << "a= "; cin >> a; cout << "b= "; cin >> b; cout << a << " / " << b << " = "; cout << k.divide(a, b); break; case 5: //power cout << "a= "; cin >> a; cout << "b= "; cin >> b; cout<< a<<"^"<<b<<" = "; cout<< k.power(a,b); break; case 6: cout << "a= "; cin >> a; cout<<k.loggy(a); break; case 7: cout<< "a= "; cin >> a; cout<<a<<"! is: "<<k.factorial(a)<<endl; break; default: cout << "Invalid Input..."; break; } cout<<endl<<"Do you want to perform another operation? Press 1 for yes or 0 to stop."<<endl; cin>>i; } return 0; }
Comments
Post a Comment