/*本程序是一个简单的计算器模拟程序。对任意给定的正确的四则表达式,程序计算其结果值并输出。表达式中运算分量为无
正负号整数,运算符为+ - * / ,圆括号按常规配对,表达式以“=”结束。函数getach()为获取表达式的一个合法字符,
并将字符存入变量curch;函数指针数组func[]是为了统一加减乘除计算而设置的。*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int add_fun(int x,int y){return x+y;}
int sub_fun(int x,int y){return x-y;}
int mul_fun(int x,int y){return x*y;}
int div_fun(int x,int y){return x/y;}
int (*func[])(int ,int)={add_fun,sub_fun,mul_fun,div_fun};
int num,curch;
char chtbl[]="+-*/()=";
char corch[]="+-*/()=0123456789";
int getach()
{
int i;
while(1)
{
curch=getchar();
if(curch==EOF)
exit(0);
for(i=0;corch[i]&&curch!=corch[i];i++);
if(i<strlen(corch))
break;
}
return curch;
}
int getid()
{
int i;
if(curch>='0'&&curch<='9')
{
for(num=0;curch>='0'&&curch<='9';getach())
num=num=10*num+(curch-'0');
return -1;
}
else
{
for(i=0;chtbl[i];i++)
if(chtbl[i]==curch)
break;
if(i<=5)
getach();
return i;
}
}
int cal()
{
int x1,x2,x3,op1,op2,i;
i=getid();
if(i==4)
x1=cal();
else
x1=num;
op1=getid();
if(op1>=5)
return x1;
i=getid();
if(i==4)
x2=cal();
else
x2=num;
op2=getid();
while(op2!=6 && op2!= 5)
{
i=getid();
if(i==4)
x3=cal();
else
x3=num;
if((op1/2==0)&&(op2/2==1))
x2=(*func[op2])(x2,x3);
else
{
x1=(*func[op1])(x1,x2);
x2=x3;
op1=op2;
}
op2=getid();
}
return (*func[op1])(x1,x2);
}
int main(int argc,char* argv[])
{
int value;
printf("please input an expression:\n");
getach();
while(curch!='=')
{
value=cal();
printf("the result is:%d\n",value);
printf("please input an expression:\n");
getach();
}
return 0;
}
腾讯实习笔试题--简单计算器程序的c语言实现
最新推荐文章于 2021-08-09 18:55:12 发布