
想要利用if和switch去描述计算的先后顺序,我应该采用什么样的方式去进行呢,需要分别判断第一个与第二个的计算符号吗,语言是c语言

可以先判断第二个运算符,如果第二个运算符是乘法或者除法,就先计算b和c。否则就依次计算。
运行结果:

使用if else 和switch的代码:
#include <stdio.h>
int main()
{
double a,b,c;
char op1,op2; //2个操作符
double res; //结果
scanf("%lf%c%lf%c%lf",&a,&op1,&b,&op2,&c);
if(op2=='*'||op2=='/') //如果第二个操作符是乘法或者除法,先计算后面的操作,因为前面的不管是什么运算符,都不影响最终结果
{
if(op2=='*')
res = (double)b*c;
else
{
if(c==0)
{
printf("除数不能为0\n");
return 0;
}else
res = (double)b/c;
}
switch(op1) //处理第一个操作符
{
case '+':
res = a + res;break;
case '-':
res = a - res;break;
case '*':
res = a * res;break;
case '/':
res = a / res;break;
}
}else
{
//依次计算,先计算第一个运算符
switch(op1)
{
case '+':
res = a + b;break;
case '-':
res = a - b;break;
case '*':
res = a * b;break;
case '/':
if(b==0)
{
printf("除数不能为0\n");
return 0;
}
else
res = a / b;
break;
}
//处理第二个运算符
switch(op2)
{
case '+':
res = res + c;break;
case '-':
res = res - c;break;
}
}
printf("%g%c%g%c%g=%g",a,op1,b,op2,c,res);
return 0;
}