用c++编写一个带异常处理的程序

2025-05-17 14:27:12
推荐回答(1个)
回答(1):

#include
#include
#include

using namespace std;

class Error
{
public:
virtual void what() = 0;
};
class addError : public Error
{
public:
void what () {cout << "ERROR: At least one of the operands is less than 10." << endl;}
};

class subError : public Error
{
public:
void what () { cout << "ERROR: At least one of the operands is not greater than 0." << endl;}
};

class mulError : public Error
{
public:
void what () { cout << "ERROR: At least one of the operands is a float." << endl; };
};

class divError : public Error
{
public:
void what () { cout << "ERROR: The divisor is 0 ." << endl;}
};

class simpleCal
{
public:
double addtion();
double subtraction();
int multiplication();
double division();
private:
double rhs;
double lhs;
void normalInput();
};
void simpleCal::normalInput()
{
cout << "Enter the 2 operands: " << endl;
cin >> rhs >> lhs;
}
double simpleCal::addtion()
{
normalInput();
if (rhs < 0 || lhs < 0)
{
throw addError();
}

return rhs + lhs;
}

double simpleCal::subtraction()
{
normalInput();
if (rhs <= 10 || lhs <= 10)
{
throw subError();
}

return rhs - lhs;
}

int simpleCal::multiplication()
{
string str1, str2;
cout << "Enter 2 operands: " << endl;
cin >> str1 >> str2;

if (str1.find('.') != string::npos || str2.find('.') != string::npos)
{
throw mulError();
}

stringstream istream;
istream << str1;
istream >> rhs;
istream.clear();

istream << str2;
istream >> lhs;
istream.clear();

return rhs * lhs;
}

double simpleCal::division()
{
normalInput();
if (lhs == 0)
{
throw divError();
}

return rhs * 1.0 / lhs;
}

int main()
{
simpleCal iCal;
char oper;

bool loop = true;
while (loop)
{
cout << "\n\nEnter the operator(+,-,*,/,other for Exit.): " << endl;
cin >> oper;
try
{
switch (oper)
{
case '+':
cout << "\nThe result is " << iCal.addtion() << endl;
break;
case '-':
cout << "\nThe result is " << iCal.subtraction() << endl;
break;
case '*':
cout << "\nThe result is " << iCal.multiplication() << endl;
break;
case '/':
cout << "\nThe result is " << iCal.division() << endl;
break;
default:
loop = false;
}
}
catch(Error& e)
{
e.what();
}

}

return 0;

}