c++用一个计算器类,让用户选择加减乘除进行运算,并要有异常处理,写好了代码还是有点乱,求帮忙修改。
#include<iostream>#include<string>usingnamespacestd;classCalculator{private:intx,y;pu...
#include<iostream>
#include<string>
using namespace std;
class Calculator
{
private:
int x,y;
public:
int jia();
int jian();
int cheng();
int chu();
};
int Calculator ::jia()
{
return x+y;
}
int Calculator ::jian()
{
return x-y;
}
int Calculator ::cheng()
{
return x*y;
}
int Calculator ::chu()
{
return x/y;
}
int main()
{
int x,y;
char c;
cout<<"请输入两个整数"<<endl;
try
{
cin>>x;
cin>>y;
}
catch(double)
{
cout<<"输入错误"<<endl;
}
throw x;
cout<<"请输入要进行的运算符合"<<endl;
switch(c)
{
case'+':
jia();
case'-':
jian();
case'*':
cheng();
case'/':
chu();
}
return 0;
} 展开
#include<string>
using namespace std;
class Calculator
{
private:
int x,y;
public:
int jia();
int jian();
int cheng();
int chu();
};
int Calculator ::jia()
{
return x+y;
}
int Calculator ::jian()
{
return x-y;
}
int Calculator ::cheng()
{
return x*y;
}
int Calculator ::chu()
{
return x/y;
}
int main()
{
int x,y;
char c;
cout<<"请输入两个整数"<<endl;
try
{
cin>>x;
cin>>y;
}
catch(double)
{
cout<<"输入错误"<<endl;
}
throw x;
cout<<"请输入要进行的运算符合"<<endl;
switch(c)
{
case'+':
jia();
case'-':
jian();
case'*':
cheng();
case'/':
chu();
}
return 0;
} 展开
展开全部
#include<iostream>
#include<string>
using namespace std;
class Calculator
{
private:
int x,y;
public:
int jia();
int jian();
int cheng();
int chu();
void show();
Calculator(int x,int y);
};
Calculator ::Calculator(int x,int y)
{
this->x = x;
this->y = y;
}
int Calculator ::jia()
{
return x+y;
}
int Calculator ::jian()
{
return x-y;
}
int Calculator ::cheng()
{
return x*y;
}
int Calculator ::chu()
{
return x/y;
}
int main()
{
int x,y;
char c;
cout<<"请输入两个整数"<<endl;
try
{
cin>>x;
cin>>y;
}
catch(double)
{
cout<<"输入错误"<<endl;
}
cout<<"请输入要进行的运算符合"<<endl;
cin>>c;
Calculator calc(x,y);
switch(c)
{
case'+':
cout<<calc.jia();
break;
case'-':
cout<<calc.jian();
break;
case'*':
cout<<calc.cheng();
break;
case'/':
cout<<calc.chu();
break;
}
return 0;
}
主要是给Calculator增加了一个构造函数,否则Calculator的x和y无法初始化,那么所有计算操作都无操作对象。
然后main里面将各个操作改为使用Calculator 对象的成员函数进行,并输出结果。
更多追问追答
追问
谢谢呀。然后异常处理try,catch那里该怎么修改呢~
追答
可以在catch里面的
cout<<"输入错误"<<endl;
下面加一句
return -1;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询