当前位置:编程学习 > C/C++ >>

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

编写一个可以进行加减乘除运算的程序,由用户输入两个数并选择要进行的运算.要求:如果作加法运算,要求两个数不小于0;做减法运算,两个数要大于10;做乘法运算,两个数不能是浮点数;做除法运算,除数不能为0.检验用户的输入时使用异常处理...
答案:
#include <iostream>
#include <string>
#include <sstream>

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 易做图Cal
{
public:
double addtion();
double subtraction();
int multiplication();
double division();
private:
double rhs;
double lhs;
void normalInput();
};
void 易做图Cal::normalInput()
{
cout << "Enter the 2 operands: " << endl;
cin >> rhs >> lhs;
}
double 易做图Cal::addtion()
{
normalInput();
if (rhs < 0 || lhs < 0)
{
throw addError();
}

return rhs + lhs;
}

double 易做图Cal::subtraction()
{
normalInput();
if (rhs <= 10 || lhs <= 10)
{
throw subError();
}

return rhs - lhs;
}

int 易做图Cal::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 易做图Cal::division()
{
normalInput();
if (lhs == 0)
{
throw divError();
}

return rhs * 1.0 / lhs;
}

int main()
{
易做图Cal 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;

}

上一个:用C++编写运动会分数统计并求平均值
下一个:C++文件用VISUAL stduio 2008写出来要怎么编译?

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,