#include#define MaxLength 50
void Show_screen()
{
printf("####################################################\n");
printf("#依次输入操作数1、运算符和操作数2,例如:2+5。 #\n");
printf("#按回车键显示运算结果,其可作为下一个输入的操作数。#\n");
printf("#按键c清除屏幕,按键r返回菜单。 #\n");
printf("####################################################\n");
}
double myadd(double x, double y)
{
double sum;
sum=x+y;
if(sum-(int)sum==0)
printf("%.0f",sum);
else
printf("%.6f",sum);
return sum;
}
double mysub(double x, double y)
{
double sub;
sub=x-y;
if(sub-(int)sub==0)
printf("%.0f",sub);
else
printf("%.6f",sub);
return sub;
}
double mymul(double x, double y)
{
double mul;
mul=x*y;
if(mul-(int)mul==0)
printf("%.0f",mul);
else
printf("%.6f",mul);
return mul;
}
double mydiv(double x, double y)
{
double div;
div=x/y;
if(div-(int)div==0)
printf("%.0f",div);
else
printf("%.6f",div);
return div;
}
int main()
{
int myoffset;
int flag;//判断是否将上次计算结果作为下次运算操作数1的标志,是的话值为1。
//只要不按+、-、*、/键,表示不作为,否则,表示作为。
char *check_add,*check_sub,*check_mul,*check_div;
char myinput[MaxLength];
char tempx[MaxLength],tempy[MaxLength];
static double res;//保存计算结果
Show_screen();
//暂不考虑字符串合法性及溢出
while(scanf("%s",myinput))
{
//printf("请输入运算表达式:\n");
check_add=strchr(myinput, +);
check_sub=strchr(myinput,-);
check_mul=strchr(myinput,*);
check_div=strchr(myinput,/);
//判断flag
if(myinput[0]==+||myinput[0]==-||myinput[0]==*||myinput[0]==/)
flag=1;
else
flag=0;
//调用清屏操作,Linux下有所不同
if(myinput[0]==c||myinput[0]==C)
system("clear");
//Windows下使用下面一行代码
//system("CLS");
//返回菜单
else if(myinput[0]==r||myinput[0]==R)
Show_screen();
//匹配加法
else if(check_add)
{
if(flag==0)
{
myoffset=(unsigned int)check_add-(unsigned int)myinput;
strncpy(tempx,myinput,myoffset);
strcpy(tempy,check_add+1);
tempx[myoffset]=\0;
tempy[strlen(myinput)-myoffset-1]=\0;
res=myadd(atof(tempx),atof(tempy));
}
else
{
strcpy(tempy,check_add+1);
res=myadd(res,atof(tempy));
}
}
else if(check_mul)
{
if(flag==0)
{
myoffset=(unsigned int)check_mul-(unsigned int)myinput;
strncpy(tempx,myinput,myoffset);
strcpy(tempy,check_mul+1);
tempx[myoffset]=\0;
tempy[strlen(myinput)-myoffset-1]=\0;
res=mymul(atof(tempx),atof(tempy));
}
else
{
strcpy(tempy,check_mul+1);
res=mymul(res, atof(tempy));
}
}
else if(check_div)
{
if(flag==0)
{
myoffset=(unsigned int)check_div-(unsigned int)myinput;
strncpy(tempx,myinput,myoffset);
strcpy(tempy,check_div+1);
tempx[myoffset]=\0;
tempy[strlen(myinput)-myoffset-1]=\0;
res=mydiv(atof(tempx),atof(tempy));
}
else
{
strcpy(tempy,check_div+1);
res=mydiv(res, atof(tempy));
}
}
//考虑到负数的存在,减法最后判断
else if(check_sub)
{
if(flag==0)
{
myoffset=(unsigned int)check_sub-(unsigned int)myinput;
strncpy(tempx,myinput,myoffset);
strcpy(tempy,check_sub+1);
tempx[myoffset]=\0;
tempy[strlen(myinput)-myoffset-1]=\0;
res=mysub(atof(tempx),atof(tempy));
}
else
{
strcpy(tempy,check_sub+1);
res=mysub(res, atof(tempy));
}
}
else
{
printf("输入有误!程序将关闭!\n");
break;
}
}
return 0;
}