用C语言编写带括号的四则运算

2024-11-24 06:00:57
推荐回答(1个)
回答1:

#include
#include "windows.h"
main()
{
char Exp[1024]={0},Oper[100]={0};
int Num[200]={0},Expi=0,Operi=0,Numi=0;
boolean isnum=FALSE;
printf("input a Expression:");
scanf("%s",Exp);
while(Exp[Expi]!='\0')
{
switch(Exp[Expi]) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
Num[Numi]=Num[Numi]*10+Exp[Expi]-'0';
isnum=TRUE;
break;
}

case '+':
case '-':
{
if(isnum) //又录入一个新数据
{
Numi++;
isnum=FALSE;
}
while(Operi!=0&&Oper[Operi-1]!='(')
{
if(Operi<1||Numi<2)
{
printf("Expression is error!\n");
exit(0);
}
switch(Oper[Operi-1]) {
case '+':
Num[Numi-2]=Num[Numi-2]+Num[Numi-1];
Num[Numi-1]=0;
Numi--;
Oper[Operi-1]='\0';
Operi--;
break;
case '-':
Num[Numi-2]=Num[Numi-2]-Num[Numi-1];
Num[Numi-1]=0;
Numi--;
Oper[Operi-1]='\0';
Operi--;
break;
case '*':
Num[Numi-2]=Num[Numi-2]*Num[Numi-1];
Num[Numi-1]=0;
Numi--;
Oper[Operi-1]='\0';
Operi--;
break;
case '/':
Num[Numi-2]=Num[Numi-2]/Num[Numi-1];
Num[Numi-1]=0;
Numi--;
Oper[Operi-1]='\0';
Operi--;
break;
}
}
Oper[Operi]=Exp[Expi];
Operi++;
break;
}