使用选择语句让程序识别有两个操作符的表达式,我感觉自己写的复杂了。大家看看能不
如题,一个练习题目,使用if...else和switch语句实现程序识别两个操作符的表达示.可不可以有比较简单的思路?但是限制在只使用if..else和switch的情况下。
#include <iostream.h>
int main()
{
float a,b,c;
char oper1,oper2;
cout<<"请输入一个表达式:"<<endl;
cin>>a>>oper1>>b>>oper2>>c;
switch(oper1)
{
case '+':
{
switch(oper2)
{
case '+':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a+b+c<<endl;
break;
case '-':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a+b-c<<endl;
break;
case '*':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a+b*c<<endl;
break;
case '/':
{
if(c!=0) cout<<a<<oper1<<b<<oper2<<c<<'='<<a+b/c<<endl;
else cout<<"Error!"<<endl;
break;
}
default:
cout<<"Error!"<<endl;
}
break;
}
case '-':
{
switch(oper2)
{
case '+':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a-b+c<<endl;
break;
case '-':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a-b-c<<endl;
break;
case '*':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a-b*c<<endl;
break;
case '/':
{
if(c!=0) cout<<a<<oper1<<b<<oper2<<c<<'='<<a-b/c<<endl;
else cout<<"Error!"<<endl;
break;
}
default:
cout<<"Error!"<<endl;
}
break;
}
case '*':
{
switch(oper2)
{
case '+':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a*b+c<<endl;
break;
case '-':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a*b-c<<endl;
break;
case '*':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a*b*c<<endl;
break;
case '/':
{
if(c!=0) cout<<a<<oper1<<b<<oper2<<c<<'='<<a*b/c<<endl;
else cout<<"Error!"<<endl;
break;
}
default:
cout<<"Error!"<<endl;
}
break;
}
case '/':
{
if(b!=0)
{
{
switch(oper2)
{
case '+':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a/b+c<<endl;
break;
case '-':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a/b-c<<endl;
break;
case '*':
cout<<a<<oper1<<b<<oper2<<c<<'='<<a/b*c<<endl;
case '/':
{
if(c!=0)
cout<<a<<oper1<<b<<oper2<<c<<'='<<a/b/c<<endl;
else
cout<<"Error!"<<endl;
break;
}
default:
cout<<"Error!"<<endl;
}
}
}
}
default:
cout<<"Error!"<<endl;
}
return 0;
}
时间仓促,没有全面的调试这个程序,应该不会有大问题