Create a calculator for the number by creating a class of number with overloading all operators in it.(Operators: ++,--,+,-,/,*, >>, <<).
#include <iostream>
using namespace std;
class Number
{
private:
float _num;
public:
void SetNum(float number)
{
_num = number;
}
float GetNum() const
{
return _num;
}
Number& operator++()
{
this->SetNum(GetNum()+1);
return *this;
}
Number& operator--()
{
this->SetNum(GetNum()-1);
return *this;
}
Number& operator=(const Number &numToAssign)
{
this->SetNum(numToAssign.GetNum());
return *this;
}
Number operator+(const Number &numToAdd)
{
this->SetNum(this->GetNum() + numToAdd.GetNum());
return *this;
}
Number operator-(const Number &numToAdd)
{
this->SetNum(this->GetNum() - numToAdd.GetNum());
return *this;
}
Number operator*(const Number &numToAdd)
{
this->SetNum(this->GetNum() * numToAdd.GetNum());
return *this;
}
Number operator/(const Number &numToAdd)
{
this->SetNum(this->GetNum() / numToAdd.GetNum());
return *this;
}
friend ostream& operator<< (ostream &out, const Number &number)
{
out << number._num;
return out;
}
friend istream& operator>> (istream &in, Number &number)
{
in >> number._num;
return in;
}
};
int main()
{
int choice;
Number number1, number2;
cout << "Enter 1 to sum 2 Numbers"
<< "\nEnter 2 to difference 2 Numbers"
<< "\nEnter 3 to multiply 2 Numbers"
<< "\nEnter 4 to divide 2 Numbers"
<< "\nEnter 5 to increase Number by 1"
<< "\nEnter 6 to decrease Number by 1"
<< "\nEnter 0 To Exit"
<< "\n";
do {
cout << "\nChoose the operation: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Please enter the first number: ";
cin >> number1;
cout << "Please enter the second number: ";
cin >> number2;
cout << "Result: " << number1 + number2 << endl;
break;
case 2:
cout << "Please enter the first number: ";
cin >> number1;
cout << "Please enter the second number: ";
cin >> number2;
cout << "Result: " << number1 - number2 << endl;
break;
case 3:
cout << "Please enter the first number: ";
cin >> number1;
cout << "Please enter the second number: ";
cin >> number2;
cout << "Result: " << number1 * number2 << endl;
break;
case 4:
cout << "Please enter the first number: ";
cin >> number1;
while(number2.GetNum() == 0)
{
cout << "Please enter the second number(not 0): ";
cin >> number2;
}
cout << "Result: " << number1/number2 << endl;
break;
case 5:
cout << "Please enter the number: ";
cin >> number1;
cout << "Result: " << ++number1 << endl;
break;
case 6:
cout << "Please enter the number: ";
cin >> number1;
cout << "Result: " << --number1 << endl;
break;
}
} while (choice >= 1 && choice <= 6);
return 0;
}
Comments
Leave a comment