# 二元表达式计算

``1*4-5``

``-1``

``````#include <stdio.h>
int calc(int num1,int num2,char oper)
{
switch(oper)
{
case '+':
return num1+num2;
case '-':
return num1-num2;
case '*':
return num1*num2;
case '/':
return num1/num2;
}
return 0;
}
int main()
{
int num1,num2,num3,priority1,priority2,result;
char oper1[2],oper2[2];
scanf("%d%[-+*/]%d%[-+*/]%d",&num1,oper1,&num2,oper2,&num3);
priority1 = (oper1[0]=='+'||oper1[0]=='-')?1:2;
priority2 = (oper2[0]=='+'||oper2[0]=='-')?1:2;
if(priority1>=priority2)
{
result =calc(num1,num2,oper1[0]);
result =calc(result,num3,oper2[0]);
}
else
{
result =calc(num2,num3,oper2[0]);
result =calc(num1,result,oper1[0]);
}
printf("%d",result);
return 0;
}
``````

``````#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
int IsOperator(char str);
char label[100];//原始输入字符串
int number[100]={0};
char operators[50];
memset(operators,49,'\0');
int j=0;//运算符数组下标
cin.getline(label,99,'\n');
int n=strlen(label);
int result=0;//结记录变量
int h=0;
for(int i=0;i<n;i++)
{
if(IsOperator(label[i])==0)//判断字符是否为运算符，不是存储数据在number数组中
{
int numbers=i;
while(IsOperator(label[numbers+1])==0&&label[numbers+1]!='\0')
{
numbers++;
}
int m=numbers-i;
for(int k=i;k<=numbers&&m>=0;k++)
{
int c=(int)label[k]-48;
number[h]+=floor(c*pow(10,m--)+0.5);
}
h++;
i=numbers;
}
else                        //是运算符则把运算符存储在operators数组中，j全局变量纪录下标
{
char op[5]="+-*/";
operators[h++]=op[IsOperator(label[i])-1];
}
}
int y=0;
for(int i=0;i<=h;i++)//对数据的正负进行处理
{
if(y==1)
{
number[i]=number[i]*-1;
y=0;
}
else if(y==0&&(int)operators[i]==45)
{
y=1;
operators[i]=' ';
}
}
for(int i=0;i<=h;i++)//进行乘除运算
{

if(operators[i]=='*'||operators[i]=='/')//如果为乘除运算，则以i为下标中心向两边取数字
{
int j;
int a=0,b=0;
for(j=0;a==0||b==0;j++)
{
if(number[i-j]!=0)
{
a=number[i-j];
number[i-j]=0;
}
if(number[i+j]!=0)
{
b=number[i+j];
number[i+j]=0;
}
}
if(operators[i]=='*')
number[i]=a*b;
else if((int)operators[i]==47)
number[i]=a/b;
i=i+j;
}
}
for(int i=0;i<=h;i++)
{
result+=number[i];
}
cout<<result<<endl;
}
int IsOperator(char str)
{
if(str!='*'&&str!='+'&&str!='/'&&str!='-')
return 0;
else if(str=='+')
return 1;
else if(str=='-')
return 2;
else if(str=='*')
return 3;
else if(str=='/')
return 4;
}
``````