C语言表达式计算器代码
C语言实现简单计算器

C语⾔实现简单计算器本⽂实例为⼤家分享了C语⾔实现简单计算器的具体代码,供⼤家参考,具体内容如下实现效果如图:实现代码如下:#include<stdio.h>#include<windows.h>//gotoxy#include<conio.h>#define width 80#define height 30void gotoxy(int x, int y);void GreateFrame(){int i = 0;for (i = 0 ; i < width; i += 2){gotoxy(i, 0); printf("■");gotoxy(i, height); printf("■");}for (i = 0; i < height + 1; i++){gotoxy(0 , i); printf("■");gotoxy(width, i); printf("■");}}void Add(){float i, j;printf("*加法运算*\n");scanf_s("%f %f", &i, &j);printf("%5.2f + %5.2f=%5.2f\n", i, j, i+j); _getch();}void Sub(){float i, j;printf("*减法运算*\n");scanf_s("%f %f", &i, &j);printf("%5.2f - %5.2f=%5.2f\n", i, j, i -j); _getch();}void Mul(){float i, j;printf("*乘法运算*\n");scanf_s("%f %f", &i, &j);printf("%5.2f * %5.2f=%5.2f\n", i, j, i * j); _getch();}void Div(){float i, j;printf("*除法运算*\n");scanf_s("%f %f", &i, &j);printf("%5.2f / %5.2f=%5.2f\n", i, j, i / j); _getch();}int main(int argc, char* argv[]){int choose;while (1){GreateFrame();gotoxy(width / 3, height / 3 + 2);printf("1.加法");gotoxy(width / 3, height / 3 + 4);printf("2.减法");gotoxy(width / 3, height / 3 + 6);printf("3.乘法");gotoxy(width / 3, height / 3 + 8);printf("4.除法");gotoxy(width / 3, height / 3 + 10);printf("5.退出程序");gotoxy(width / 3, height / 3);printf("请选择你要计算的⽅式:( )\b\b"); scanf_s("%d", &choose);switch (choose){case 1:system("cls");Add(); break;case 2:system("cls");Sub(); break;case 3:system("cls");Mul(); break;case 4:system("cls");Div(); break;case 5:exit(0);}system("cls");}}void gotoxy(int x, int y){COORD POS;POS.X = x;POS.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),POS);}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
计算器编程c语言

计算器编程 c语言用C语言设计计算器程序源代码#include <dos.h> /*DOS接口函数*/#include <math.h> /*数学函数的定义*/#include <conio.h> /*屏幕操作函数*/函数*/#include <stdio.h> /*I/O#include <stdlib.h> /*库函数*/变量长度参数表*/#include <stdarg.h> /*图形函数*/#include <graphics.h> /*字符串函数*/#include <string.h> /*字符操作函数*/#include <ctype.h> /*#define UP 0x48 /*光标上移键*/#define DOWN 0x50 /*光标下移键*/#define LEFT 0x4b /*光标左移键*/#define RIGHT 0x4d /*光标右移键*/#define ENTER 0x0d /*回车键*/void *rar; /*全局变量,保存光标图象*/使用调色板信息*/struct palettetype palette; /*int GraphDriver; /* 图形设备驱动*/int GraphMode; /* 图形模式值*/int ErrorCode; /* 错误代码*/int MaxColors; /* 可用颜色的最大数值*/int MaxX, MaxY; /* 屏幕的最大分辨率*/double AspectRatio; /* 屏幕的像素比*/void drawboder(void); /*画边框函数*/初始化函数*/void initialize(void); /*计算器计算函数*/void computer(void); /*改变文本样式函数*/ void changetextstyle(int font, int direction, int charsize); /*窗口函数*/void mwindow(char *header); /*/*获取特殊键函数*/int specialkey(void) ;设置箭头光标函数*//*int arrow();/*主函数*/int main(){设置系统进入图形模式 */initialize();/*运行计算器 */computer(); /*系统关闭图形模式返回文本模式*/closegraph();/*/*结束程序*/return(0);}/* 设置系统进入图形模式 */void initialize(void){int xasp, yasp; /* 用于读x和y方向纵横比*/GraphDriver = DETECT; /* 自动检测显示器*/initgraph( &GraphDriver, &GraphMode, "" );/*初始化图形系统*/ErrorCode = graphresult(); /*读初始化结果*/如果初始化时出现错误*/if( ErrorCode != grOk ) /*{printf("Graphics System Error: %s\n",显示错误代码*/grapherrormsg( ErrorCode ) ); /*退出*/exit( 1 ); /*}getpalette( &palette ); /* 读面板信息*/MaxColors = getmaxcolor() + 1; /* 读取颜色的最大值*/MaxX = getmaxx(); /* 读屏幕尺寸 */MaxY = getmaxy(); /* 读屏幕尺寸 */getaspectratio( &xasp, &yasp ); /* 拷贝纵横比到变量中*/计算纵横比值*/ AspectRatio = (double)xasp/(double)yasp;/*}/*计算器函数*/void computer(void){定义视口类型变量*/struct viewporttype vp; /*int color, height, width;int x, y,x0,y0, i, j,v,m,n,act,flag=1;操作数和计算结果变量*/float num1=0,num2=0,result; /*char cnum[5],str2[20]={""},c,temp[20]={""};定义字符串在按钮图形上显示的符号 char str1[]="1230.456+-789*/Qc=^%";/**/mwindow( "Calculator" ); /*显示主窗口 */设置灰颜色值*//*color = 7;getviewsettings( &vp ); /* 读取当前窗口的大小*/width=(vp.right+1)/10; /* 设置按钮宽度 */设置按钮高度 */height=(vp.bottom-10)/10 ; /*/*设置x的坐标值*/x = width /2;设置y的坐标值*/y = height/2; /*setfillstyle(SOLID_FILL, color+3);bar( x+width*2, y, x+7*width, y+height );/*画一个二维矩形条显示运算数和结果*/setcolor( color+3 ); /*设置淡绿颜色边框线*/rectangle( x+width*2, y, x+7*width, y+height );/*画一个矩形边框线*/设置颜色为红色*/setcolor(RED); /*输出字符串"0."*/outtextxy(x+3*width,y+height/2,"0."); /*/*设置x的坐标值*/x =2*width-width/2;设置y的坐标值*/y =2*height+height/2; /*画按钮*/for( j=0 ; j<4 ; ++j ) /*{for( i=0 ; i<5 ; ++i ){setfillstyle(SOLID_FILL, color);setcolor(RED);bar( x, y, x+width, y+height ); /*画一个矩形条*/rectangle( x, y, x+width, y+height );sprintf(str2,"%c",str1[j*5+i]);/*将字符保存到str2中*/outtextxy( x+(width/2), y+height/2, str2);移动列坐标*/x =x+width+ (width / 2) ;/*}y +=(height/2)*3; /* 移动行坐标*/x =2*width-width/2; /*复位列坐标*/}x0=2*width;y0=3*height;x=x0;y=y0;gotoxy(x,y); /*移动光标到x,y位置*/显示光标*/arrow(); /*putimage(x,y,rar,XOR_PUT);m=0;n=0;设置str2为空串*/strcpy(str2,""); /*当压下Alt+x键结束程序,否则执行下面的循环while((v=specialkey())!=45) /**/{当压下键不是回车时*/while((v=specialkey())!=ENTER) /*{putimage(x,y,rar,XOR_PUT); /*显示光标图象*/if(v==RIGHT) /*右移箭头时新位置计算*/if(x>=x0+6*width)如果右移,移到尾,则移动到最左边字符位置*//*{x=x0;m=0;}else{x=x+width+width/2;m++;否则,右移到下一个字符位置*/} /*if(v==LEFT) /*左移箭头时新位置计算*/if(x<=x0){x=x0+6*width;m=4;} /*如果移到头,再左移,则移动到最右边字符位置*/else{x=x-width-width/2;m--;} /*否则,左移到前一个字符位置*/if(v==UP) /*上移箭头时新位置计算*/if(y<=y0){y=y0+4*height+height/2;n=3;} /*如果移到头,再上移,则移动到最下边字符位置*/else{y=y-height-height/2;n--;} /*否则,移到上边一个字符位置*/if(v==DOWN) /*下移箭头时新位置计算*/if(y>=7*height){ y=y0;n=0;} /*如果移到尾,再下移,则移动到最上边字符位置*/else{y=y+height+height/2;n++;} /*否则,移到下边一个字符位置*/putimage(x,y,rar,XOR_PUT); /*在新的位置显示光标箭头*/ }将字符保存到变量c中*/c=str1[n*5+m]; /*判断是否是数字或小数点*/if(isdigit(c)||c=='.') /*{如果标志为-1,表明为负数*/if(flag==-1) /*{将负号连接到字符串中*/strcpy(str2,"-"); /*flag=1;} /*将标志值恢复为1*/将字符保存到字符串变量temp中*/ sprintf(temp,"%c",c); /*将temp中的字符串连接到str2中*/strcat(str2,temp); /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);显示字符串*/outtextxy(5*width,height,str2); /*}if(c=='+'){将第一个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*做计算加法标志值*/act=1; /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='-'){如果str2为空,说明是负号,而不是减号*/ if(strcmp(str2,"")==0) /*设置负数标志*/flag=-1; /*else{将第二个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*act=2; /*做计算减法标志值*/setfillstyle(SOLID_FILL,color+3);画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}}if(c=='*'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算乘法标志值*/act=3; /*setfillstyle(SOLID_FILL,color+3); bar(2*width+width/2,height/2,15*width /2,3*height/2);显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='/'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算除法标志值*/act=4; /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);outtextxy(5*width,height,"0."); /*显示字符串*/}if(c=='^'){将第二个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*做计算乘方标志值*/act=5; /*设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='%'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算模运算乘方标志值*/act=6; /*setfillstyle(SOLID_FILL,color+3); /*设置用淡绿色实体填充*/画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='='){将第二个操作数转换为浮点数*/num2=atof(str2); /*根据运算符号计算*/switch(act) /*{case 1:result=num1+num2;break; /*做加法*/case 2:result=num1-num2;break; /*做减法*/case 3:result=num1*num2;break; /*做乘法*/case 4:result=num1/num2;break; /*做除法*/case 5:result=pow(num1,num2);break; /*做x的y次方*/case 6:result=fmod(num1,num2);break; /*做模运算*/ }设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*覆盖结果区*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*将结果保存到temp中*/sprintf(temp,"%f",result); /*outtextxy(5*width,height,temp); /*显示结果*/}if(c=='c'){num1=0; /*将两个操作数复位0,符号标志为1*/num2=0;flag=1;strcpy(str2,""); /*将str2清空*/设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*覆盖结果区*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}如果选择了q回车,结束计算程序*/if(c=='Q')exit(0); /*}putimage(x,y,rar,XOR_PUT); /*在退出之前消去光标箭头*/返回*/return; /*}/*窗口函数*/void mwindow( char *header ){int height;cleardevice(); /* 清除图形屏幕 */setcolor( MaxColors - 1 ); /* 设置当前颜色为白色*//* 设置视口大小 */ setviewport( 20, 20, MaxX/2, MaxY/2, 1 );height = textheight( "H" ); /* 读取基本文本大小 */settextstyle( DEFAULT_FONT, HORIZ_DIR, 1 );/*设置文本样式*/settextjustify( CENTER_TEXT, TOP_TEXT );/*设置字符排列方式*/输出标题*/outtextxy( MaxX/4, 2, header ); /*setviewport( 20,20+height+4, MaxX/2+4, MaxY/2+20, 1 ); /*设置视口大小*/ 画边框*/drawboder(); /*}画边框*/void drawboder(void) /*{定义视口类型变量*/struct viewporttype vp; /*setcolor( MaxColors - 1 ); /*设置当前颜色为白色 */setlinestyle( SOLID_LINE, 0, NORM_WIDTH );/*设置画线方式*/将当前视口信息装入vp所指的结构中*/getviewsettings( &vp );/*画矩形边框*/rectangle( 0, 0, vp.right-vp.left, vp.bottom-vp.top ); /*}/*设计鼠标图形函数*/int arrow(){int size;定义多边形坐标*/int raw[]={4,4,4,8,6,8,14,16,16,16,8,6,8,4,4,4}; /*设置填充模式*/setfillstyle(SOLID_FILL,2); /*/*画出一光标箭头*/fillpoly(8,raw);测试图象大小*/size=imagesize(4,4,16,16); /*分配内存区域*/rar=malloc(size); /*存放光标箭头图象*/getimage(4,4,16,16,rar); /*putimage(4,4,rar,XOR_PUT); /*消去光标箭头图象*/return 0;}/*按键函数*/int specialkey(void){int key;等待键盘输入*/while(bioskey(1)==0); /*key=bioskey(0); /*键盘输入*/只取特殊键的扫描值,其余为0*/ key=key&0xff? key&0xff:key>>8; /*return(key); /*返回键值*/}。
c语言计算器代码

{
match('+'); /*进行加法运算*/
result += mid();
break;
}
else if ( token == '-')
{
match('-'); /*进行减法运算*/
result -= mid();
break;
}
return result;
}
int mid( void )/*用于计算表达式中级别较高的运算*/
#include <stdio.h>
char token;
/*定义程序要使用到的一些函数*/
void match( char expectedToken ) /*对当前的标志进行匹配*/
{
if( token == expectedToken ) token = getchar(); /*匹配成功,获取下一个标志*/
break;
}
else if (token == '/')
{
match('/'); /*进行除法运算*/
div = high();
if( div == 0 ) /*需要判断除数是否为0*/
{
printf( "除数为0.\n" );
exit(1);
}
result /= div;
break;}ret Nhomakorabearn result;
printf("**Please input a multinomial like **\n");
printf("** 6-3*(5-1)/2+14/7 **\n");
C语言实现简易计算器(可作加减乘除)

C语⾔实现简易计算器(可作加减乘除)C语⾔实现简易计算器(加减乘除)计算器作为课设项⽬,已完成答辩,先将代码和思路(注释中)上传⼀篇博客已增添、修改、整理⾄⽆错且可正常运⾏虽使⽤了栈,但初学者可在初步了解栈和结构语法后理解代码#include <stdlib.h>#include <stdio.h>#include <string.h>#define IsDouble 0#define IsChar 1//_______________________________________________________________________________________________________________________________________________________ //1.⽀持浮点数和字符的栈typedef struct {char * buffer;int typesize;int top;int max;} stack;stack * CreateStack(int max, int typesize);//创建⼀个栈void DestroyStack(stack *);//释放栈的空间void ClearStack(stack *);//清空栈int Push(stack *, void *);//⼊栈int Pop(stack *, void *);//出栈int GetSize(stack *s);//得到栈的⼤⼩int GetTop(stack *, void *);//找到栈顶int IsEmpty(stack *);//判断是否为空栈,空则下溢int IsFull(stack *);//判断栈是否已满,满则溢出stack * CreateStack(int max, int typesize){stack * s = (stack*)malloc(sizeof(stack));//为栈s malloc内存if (!s) return 0;//为结构中buffer元素malloc内存s->buffer = (char *)malloc(sizeof(char) * max * typesize);if (!s->buffer) return 0;//初始化结构中的栈顶,最⼤值,类型⼤⼩s->top = -1;s->max = max;s->typesize = typesize;return s;}void DestroyStack(stack* s){free(s->buffer);//先释放buffer的空间free(s);//在释放s的空间}void ClearStack(stack * s){s->top = -1;//清空栈(栈头位置归零)}int Push(stack * s, void * data){if (IsFull(s)) return 0;//如果栈已满则return 0,防⽌溢出//栈未满则将栈头移动打动下⼀位置,并将data中的元素拷⼊栈中buffer的第top位置s->top++;memcpy(s->buffer + s->top*s->typesize, data, s->typesize);//⼊栈成功return 1return 1;}int Pop(stack * s, void * data){if (IsEmpty(s)) return 0;//出栈判断栈是否为空,若为空则return 0//栈未空则将buffer中top位置的字符拷⼊data记录,并让栈头向前移动⼀个位置memcpy(data, s->buffer + s->top*s->typesize, s->typesize);s->top--;//成功则return 1return 1;}int GetSize(stack *s){return s -> top+1;//栈头位置+1得到⼤⼩}int GetTop(stack *s, void * data){if (IsEmpty(s)) return 0;//如果栈空return 0//栈不为空则将top位置的字符拷回data记录,得到栈头memcpy(data, s->buffer + s->top*s->typesize, s->typesize);//成功则return 1;return 1;}int IsEmpty(stack * s){return s->top == -1;//如果top为-1则栈空}int IsFull(stack * s){return s->top == s->max-1;//如果top为max-1则栈满}//___________________________________________________________________________________________________________________________________________________ //2.定义⼀个cal类型,其中data存数时sign为IsDouble,存字符时,sign为Ischartypedef struct {double data;char sign;} cal;//3.查找对应符号(找到则返回该符号下标)(找不到则说明该部分为数字返回-1)int SearchCode(char ch){char * code = "+-*/()@";//@为终⽌符,算式输⼊结束int index = 0;//while (code[index]){if (code[index] == ch) return index;index++;}return -1;}//4.得到两个符号间的优先级//与SearchCode相对应,char GetPriority(char ch, char next){//创建⼀个perferen表,第i⾏(列)对应SearchCode函数中code中的第i个字符char perferen[7][7] = {">><<<>>",">><<<>>",">>>><>>",">>>><>>","<<<<<=E",">>>>E>>","<<<<<E="};//找到两个形参对应的字符int c = SearchCode(ch);int n = SearchCode(next);//如果找不到对应运算符(字符不是运算符⽽是为数字)return Eif (c==-1 || n==-1) return 'E';//如果找到两个对应运算符则按照优先级表返回两个运算符的优先级return perferen[c][n];}//5.四则运算double add(double a, double b) { return a+b; }double sub(double a, double b) { return a-b; }double mul(double a, double b) { return a*b; }double ddiv(double a, double b) { return a/b; }//整合四种运算double calcu(double a, char ch, double b){double (*calculation[4])(double,double) = {add,sub,mul,ddiv};return calculation[SearchCode(ch)](a,b);}//6.检测字符串int CheckStr(char * buffer){int n;//遍历字符串确保算式中⽆⾮法字符若检测到⾮法字符return 0,若都合法则return 1for (n = 0;buffer[n];n++){if ((SearchCode(buffer[n]) != -1 || buffer[n] == '.' || (buffer[n] >= '0' && buffer[n] <= '9')) && buffer[n] != '@') continue;else return 0;}buffer[n] = '@';//加上终⽌符,表⽰算式结束buffer[n+1] = '\0';return 1;}//7.得到数据转化为double类型存⼊rsint GetDigit(char * buffer, int * n, double * rs){char str[30];int i,j = 0;for (i = 0;SearchCode(buffer[*n]) == -1;i++){str[i] = buffer[*n];//从*n位置开始,将这⼀串数字字符存⼊str(*n)++;}str[i] = '\0';for (i = 0;str[i];i++){if (str[i] == '.') j++;}//如果⼀段⼩数有多个⼩数点或⼩数点在数字⾸尾,return 0if (j>1 || str[i-1] == '.' || str[0] == '.') return 0;//rs接收转化为double的数据*rs = atof(str);//操作成功return 1return 1;}//8.将⽤户输⼊的buffer字符串转化为可供程序运算的calstr数组int resolu(char * buffer, cal * calstr){int i = 0, j = 0;cal c;while (buffer[i]){if (SearchCode(buffer[i]) == -1){//如果得到数据不成功则return 0if (GetDigit(buffer,&i, &c.data) == 0) return 0;//如果成功得到数据则在c.sign标记为浮点数c.sign = IsDouble;//将c存⼊数组calstr中calstr[j++] = c;}else{//若符号为运算符//判断正负号if (buffer[i] == '-' && (buffer[i-1] == '('||buffer[i-1] == '+'||buffer[i-1] == '-'||buffer[i-1] == '*'||buffer[i-1] == '/') || (i==0 && buffer[0] == '-')){ i++;if (GetDigit(buffer,&i, &c.data) == 0) return 0;//在符号的下⼀位开始查找,若找不到数字return 0//否则,给数字取相反数,c.sign标记为浮点数,存⼊calstr中c.data = 0 - c.data;c.sign = IsDouble;calstr[j++] = c;} else//如果是正号,与符号处理⽅式同理if (buffer[i] == '+' && (buffer[i-1] == '('||buffer[i-1] == '+'||buffer[i-1] == '-'||buffer[i-1] == '*'||buffer[i-1] == '/') || (i==0 && buffer[0] == '+')){ i++;if (GetDigit(buffer, &i, &c.data) == 0) return 0;c.sign = IsDouble;calstr[j++] = c;}else{//如果不是正负号,则为运算符,先强制转换为double类型存在c.data⾥,然后c.sign标记为char类型,存⼊calstrc.data = (double)buffer[i++];c.sign = IsChar;calstr[j++] = c;}}}//操作蔡成功则return 1return 1;}//9.计算出结果int result(cal * calstr, double * rs){stack * pst = CreateStack(100,sizeof(char));//运算符栈stack * pnd = CreateStack(100,sizeof(double));//数据栈double num1,num2;int n = 0;char ch = '@';Push(pst, &ch);//在转换得到的calstr中遍历直到终⽌符'@"while(ch != '@' || !(calstr[n].sign == IsChar && (char)calstr[n].data == '@')){//如果calstr的n位上是浮点数,则将这个data压栈进⼊数据栈pnd中if (calstr[n].sign == IsDouble){Push(pnd, &(calstr[n].data));n++;}//反之,如果是运算符,则要检测优先级else{switch( GetPriority(ch, (char)calstr[n].data)){//如果运算符优先级较⼩,则让ch等于优先级⼤的符号并压⼊符号栈pst中case '<':ch = (char)calstr[n].data;Push(pst, &ch);n++;break;//如果结果为等号,让符号出栈暂存到ch中case '=':if (!Pop(pst, &ch)) return 0;n++;break;//如果ch优先级较⾼,则将前两个数字及运算符出栈,分别储存⾄num2,ch,num1中,进⾏运算,得到的结果再次压栈进⼊pnd中 case '>':if (!(Pop(pnd,&num2) && Pop(pst,&ch) && Pop(pnd,&num1))) return 0;num1 = calcu(num1,ch,num2);Push(pnd, &num1);break;//如果符号顺序出错,return 0case 'E':return 0;}}//检测是否可以得到栈顶符号,栈空则return 0if (!GetTop(pst, &ch)) return 0;}//如果栈中得到了最终结果,并且取出pnd中的最终结果到rs,return 1if (GetSize(pnd) == 1 && GetTop(pnd,rs)){DestroyStack(pst);DestroyStack(pnd);return 1;}//否则 return 0else{return 0;}}//10.⽤户交互函数void treatment(){char buffer[100];//⽤户输⼊的字符串(算式)cal calstr[50];//计算⽤的数组double rs = 0;//计算结果printf("Enter your equation:");gets(buffer);//让⽤户输⼊算式buffer//⽤户不输⼊"exit"就不退出while (!(buffer[0]=='e' && buffer[1]=='x' && buffer[2]=='i' && buffer[3]=='t')){//检查buffer中字符君合法,成功将buffer转化为⽤于计算的calstr数组,成功计算出结果存⼊rsif (CheckStr(buffer) && resolu(buffer,calstr) && result(calstr,&rs)){printf("\n%lf\n",rs);}else{printf("\nError!\n");}printf("Enter \"exit\"to quit");printf("\nEnter your equation:");gets(buffer);//再次让⽤户输⼊算式}printf("\nbye\n");}//11.主函数int main(){treatment();}参考⽂献链接如下[参考⽂献]()。
c语言编写计算器

#define MAX 80#define MAX1 40#define MAX2 40#define NULL 0#include <stdio.h>#include <math.h>typedef struct{double A[ MAX1 ];int top1;}shuju;typedef struct{char B[ MAX2 ];int top2;}yunsuanfu;void chushihua1(shuju *p) {p->top1 = 0;}void chushihua2(yunsuanfu *p) {p->top2 = 0;}int charu1(shuju *p,double x) {if(p->top1 >= (MAX1 - 1)) {return 0;}else{p->A[ p->top1 ] = x;p->top1++;return 1;}}int charu2(yunsuanfu *p,char x) {if(p->top2 >= (MAX2 - 1)){printf("you are wrong2\n");return 0;}else{p->B[ p->top2 ] = x;p->top2++;return 1;}}int chuzhuan1(shuju *p,double *x) {if(p->top1 < 0){return 0;}else{p->top1--;*x=p->A[ p->top1 ];return 1;}}int chuzhuan2(yunsuanfu *p,char *x){if(p->top2 < 0){printf("you are wrong22\n");return 0;}else{p->top2--;*x=p->B[ p->top2 ];return 1;}}int op(char f,char b){if((f == '(' && b == ')') || (f == '\0' && b == '\0')) return 2;else if(((b == '*' || b == '/') && (f == '+' || f == '-'))||(b == '(' && f != ')') || ((f == '(' || f == '\0') && (b == '+' || b == '/' || b == '-' || b == '*')))return -1;else if((b == '\0' && f != '(') || (b == ')' && f != '\0') || b == f || ((f == '*' || f == '/' || f == ')') && (b == '+' || b == '/' || b == '-' || b == '*')))return 1;else{printf("\t\t\tyou are wrong\n");return 0;}}double zhuanhuan(int x,int y,char a[]){int i, j=0, k;double n=0;for(i=x; i<y; i++){if(a[ i ] != '.')n = n*10+a[ i ]-'0';else j=i;}if(j == 0)return n;else{for(k=0; k < i-1-j; k++)n = n/10;return n;}}double f1(shuju *a,yunsuanfu *b) {double m, m1, m2;char x;chuzhuan2(b, &x);chuzhuan1(a, &m1);chuzhuan1(a, &m2);if(x == '*')m = m1*m2;else if(x == '+')m = m1+m2;else if(x == '-')m = m2-m1;else if(x == '/')if(m1 == 0){printf("\t\t\tyou are wrong\n");jieshu();}elsem = m2/m1;charu1(a, m);return m;}void f2(int j, yunsuanfu *b, char k[]) {charu2(b, k[ j ]);}void jiemian(){system("cls");printf("\n");printf("\t\t\t C O U N T E R\n");textcolor(5);cprintf("*********************************************************************** ********");printf("\n\n");printf("\t\t\tPlease input your exprssion\n");printf("\t\t\t ");}jieshu(){char c;printf("Are you contiune?(y/n) ");while(1){c = getch();printf("\n");if(c == 'y' || c == 'Y')main();else if(c == 'n' || c == 'N'){system("cls");printf("\n\n\t\t\t Thank you use the counter\n");printf("\t\t\t");getch();exit(0);}else{printf("\t\t\t");cprintf("Please input y/n!");printf("\n");printf("\t\t\t");continue;}}}main(){int i=0,j=0,bi,b1,B=0;double n,m1,m2,m=0;char k[ MAX ],ch='\0',x;shuju a;yunsuanfu b;chushihua1( &a );chushihua2( &b );charu2( &b, '\0' );jiemian();gets(k);while(k[ i ] != '\0'){if(k[ j ] == 's' && k[ j+2 ] == 'n'){j = j+3;i = j;B = 1;}else if(k[ j ] == 'c' && k[ j+2 ] == 's'){j = j+3;i = j;B = 2;}else if(k[ j ] == 't' && k[ j+2 ] == 'n'){j = j+3;i = j;B = 3;}else if(k[ j ] == 'l' && k[ j+2 ] == 'g'){j = j+3;i = j;B = 4;}else if(k[ j ] == 'l' && k[ j+1 ] == 'n'){j = j+2;i = j;B = 5;}while(k[ j ] == '.' || (k[ j ] >= '0' && k[ j ] <= '9' ))j++;n=zhuanhuan(i,j,k);switch(B){case 1: n=sin(n);break; case 2: n=cos(n);break; case 3: n=tan(n);break; case 4: n=log10(n);break; case 5: n=log(n);}charu1(&a, n);b1 = 0;while(b1 == 0){bi = op(ch, k[j] );if(bi == 0)jieshu();while(bi == 1){m = f1(&a, &b);chuzhuan2(&b, &ch);bi = op(ch, k[ j ]);charu2(&b, ch);}if(bi == -1){do{f2(j, &b,k);j++;}while(k[j ] == '(');j--;}else if(bi == 2){if(ch == '('){if(k[ j ] == ')')j++;chuzhuan2(&b, &ch);chuzhuan2(&b, &ch);charu2(&b, ch);continue;}else chuzhuan1(&a, &m); }b1 = 1;}if(k[ j ] == '\0')break;else{ch = k[ j ];j++;}i = j;B = 0;}printf("\t\t\t");textcolor(30);cprintf("The answer is %f",m); printf("\n");jieshu();}。
用c语言写的简单计算器

⽤c语⾔写的简单计算器这是⾃⼰在学习C语⾔,凭借⾃⼰的兴趣,将课本的知识运⽤后整理的关于C语⾔计算器的代码。
计算器实现的功能有:加、减、乘、除、求余。
功能简单,但对于初学者的我来说能把它写出来,排除每个错误依旧是个难题。
前后两种代码是由⾃⼰所学东西的质量决定的,如有错误,请前辈指出。
最初版本的计算器:1 #include<stdio.h>23int checkPassword();45int add(int x,int y);67int sub(int x,int y);89int multi(int x,int y);1011float quo(float x1,float y1);1213int com(int x,int y);1415int x,y;1617int result;1819int select;2021float result1;2223float x1,y1;2425int success,psw;2627int a;2829int i;3031int t;323334353637void main()3839 {4041 printf("请输⼊密码:\n");4243 i=0;4445do{46474849 scanf("%d",&a);50515253if( a!=1234 && i<2)5455 printf("请重新输⼊密码:\n");5657else5859 i=3;6061 i++;6263 }while( i<=2);6465if(a==1234)6667 {6869for(t=1;t!=6;t=select)7071 {72737576777879 printf("+=============================+\n"); 8081 printf("+======计=算=器=主=菜=单======+\n"); 8283 printf("+=============================+\n"); 8485 printf("+==========1、加法==========+\n"); 8687 printf("+==========2、减法==========+\n"); 8889 printf("+==========3、乘法==========+\n"); 9091 printf("+==========4、除法==========+\n"); 9293 printf("+==========5、求余==========+\n"); 9495 printf("+==========6、退出==========+\n"); 9697 printf("+=============================+\n"); 9899100101102103 printf("请输⼊你的选择:\n");104105 scanf("%d",&select);106107108109switch(select)110111 {112113114115case1:116117 printf("请输⼊两个数:\n");118119 scanf("%d%d",&x,&y);120121 result=add(x,y);122123 printf("%d+%d=%d\n",x,y,result);124125break;126127case2:128129 printf("请输⼊两个数:\n");130131 scanf("%d%d",&x,&y);132133 result=sub(x,y);134135 printf("%d-%d=%d\n",x,y,result);136137break;138139case3:140141 printf("请输⼊两个数:\n");142143 scanf("%d%d",&x,&y);144145 result=multi(x,y);146147 printf("%d*%d=%d\n",x,y,result);148149break;150151case4:152153 printf("请输⼊两个数:\n");154155 scanf("%f%f",&x1,&y1);156157 result1=quo(x1,y1);159 printf("%f/%f=%f\n",x1,y1,result1); 160161break;162163case5:164165 printf("请输⼊两个数:\n");166167 scanf("%d%d",&x,&y);168169 result=com(x,y);170171 printf("%d/%d=%d\n",x,y,result); 172173break;174175case6:176177break;178179default:180181 printf("请输⼊1~5之间的数\n"); 182183break;184185186187188189 }190191 }192193 }194195 }196197int add(int x,int y)198199 {200201int sum;202203 sum=x+y;204205return sum;206207 }208209int sub(int x,int y)210211 {212213int sub;214215 sub=x-y;216217return sub;218219 }220221int multi(int x,int y)222223 {224225int multi;226227 multi=x*y;228229return multi;230231 }232233float quo(float x,float y)234235 {236237float quo;238239 quo=x/y;240241return quo;243 }244245int com(int x,int y)246247 {248249int com;250251 com=x%y;252253return com;254255 }256257int checkPassword( int psw)258259 {260261if(psw==1234)262263 success=1;264265else266267 success=-1;268269return success;270271 }改版后的计算器:1 #include<stdio.h>23int yanzheng(int );45void caidan();67void jiafa(int,int);89void jianfa(int,int);1011void chengfa(float,float);1213void chufa(float,float);1415void mo(int,int);16171819void main(){2021int x,m;2223int y;2425float a,b;2627 printf("请输⼊密码:\n");2829 scanf("%d",&x);3031 m=yanzheng(x);3233if(m==1){3435 caidan();3637//int y;3839//float a,b;4041for(;y!=6;){4243 printf("请输⼊选项:\n"); 4445 scanf("%d",&y);4647if(y>=1 && y<6){4849 printf("请输⼊要运算的两个数:\n");5051 scanf("%f%f",&a,&b);5253 }54555657switch(y){5859case1 :jiafa(a,b);break;6061case2 :jianfa(a,b);break;6263case3 :chengfa(a,b);break;6465case4 :chufa(a,b);break;6667case5 :mo(a,b);break;6869case6 :break;7071default : printf("选项输⼊错误!请重试\n");break; 7273 }7475 }7677 }7879 }808182838485int yanzheng(int x){8687int i,m;8889for(i=1,m=0;i<3;i++){9091if(x==1234){9293 m=1;9495break;9697 }9899 printf("请重新出⼊密码:");100101 scanf("%d",&x);102103104105 }106107return m;108109 }110111112113void caidan(){114115 printf("+=============================+\n"); 116117 printf("+======计=算=器=主=菜=单======+\n"); 118119 printf("+=============================+\n"); 120121 printf("+==========1、加法==========+\n"); 122123 printf("+==========2、减法==========+\n"); 124125 printf("+==========3、乘法==========+\n"); 126127 printf("+==========4、除法==========+\n"); 128129 printf("+==========5、求余==========+\n"); 130131 printf("+==========6、退出==========+\n"); 132133 printf("+=============================+\n"); 134135 }136137138139void jiafa(int x,int y){140141int sum;142143 sum=x+y;144145 printf("%d\n", sum);146147 }148149150151void jianfa(int x,int y){152153int cha;154155 cha=x-y;156157 printf("%d\n", cha);158159 }160161162163void chengfa(float x,float y){164165float ji;166167 ji=x*y;168169 printf("%f\n", ji);170171 }172173174175void chufa(float x,float y){176177float shang;178179 shang=x/y;180181 printf("%f\n", shang);182183 }184185186187void mo(int x,int y){188189int mo;190191 mo=x%y;192193 printf("%d\n", mo);194195 }。
C语言简易计算器的实现

C语言简易计算器的实现C语言简易计算器是一种用于进行基本数学运算的程序。
实现一个简易计算器的关键是要能够解析用户输入的数学表达式,并将其转化为计算机可以理解的形式,然后进行计算,并输出结果。
下面是一个大约1200字以上的示例实现。
```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <ctype.h>#define MAX_SIZE 100//定义操作符的优先级int getPriority(char op)if (op == '+' , op == '-')return 1;else if (op == '*' , op == '/')return 2;elsereturn 0;//进行四则运算int calculate(int a, int b, char op)switch (op)case '+': return a + b;case '-': return a - b;case '*': return a * b;case '/': return a / b;default: return 0;}//将中缀表达式转换为后缀表达式void infixToPostfix(char* infixExp, char* postfixExp) char stack[MAX_SIZE];int top = -1;int j = 0;for (int i = 0; infixExp[i] != '\0'; i++)if (isdigit(infixExp[i])) { // 数字直接输出到后缀表达式while (isdigit(infixExp[i]))postfixExp[j++] = infixExp[i++];}postfixExp[j++] = ' ';i--;}else if (infixExp[i] == '(') { // 左括号压入栈stack[++top] = infixExp[i];}else if (infixExp[i] == ')') { // 右括号弹出栈内所有操作符并输出到后缀表达式,直到遇到左括号while (top != -1 && stack[top] != '(')postfixExp[j++] = stack[top--];postfixExp[j++] = ' ';}top--; // 弹出栈顶的左括号}else { // 操作符while (top != -1 && getPriority(stack[top]) >=getPriority(infixExp[i]))postfixExp[j++] = stack[top--];postfixExp[j++] = ' ';stack[++top] = infixExp[i];}}while (top != -1) { // 将栈内剩余操作符弹出并输出到后缀表达式postfixExp[j++] = stack[top--];postfixExp[j++] = ' ';}postfixExp[j] = '\0';//计算后缀表达式的值int evaluatePostfix(char* postfixExp)char stack[MAX_SIZE];int top = -1;for (int i = 0; postfixExp[i] != '\0'; i++)if (isdigit(postfixExp[i])) { // 数字压入栈int num = 0;while (isdigit(postfixExp[i]))num = num * 10 + (postfixExp[i++] - '0');stack[++top] = num;i--;}else if (postfixExp[i] == ' ')continue;}else { // 操作符,弹出栈顶的两个数进行计算,并将结果压入栈int b = stack[top--];int a = stack[top--];int result = calculate(a, b, postfixExp[i]);stack[++top] = result;}}return stack[top];int maichar infixExp[MAX_SIZE];printf("请输入中缀表达式:");fgets(infixExp, sizeof(infixExp), stdin); // 读取用户输入//将中缀表达式转换为后缀表达式char postfixExp[MAX_SIZE];infixToPostfix(infixExp, postfixExp);printf("后缀表达式为:%s\n", postfixExp);//计算后缀表达式的值并输出int result = evaluatePostfix(postfixExp);printf("计算结果为:%d\n", result);return 0;```这个简易计算器的实现基于栈的数据结构。
C语言 计算器

// counter2.cpp : Defines the entry point for the console application.// 实现计算器,+,- * / 小数#define MAXSIZE 100#define END '\n'#include "stdio.h"#include "stdlib.h"#include "math.h"/*1.支持高位+小数加减乘除运算123.4562.支持正负数8*+2 8*-23.对输入有误的警报(数栈和符号栈内还有余留,以及几个特殊的设定)4.支持幂指数运算a^n (n为整数)5.还有a的阶乘运算不足之处:老师给的那些定义的错误不能放入循环中,程序就会结束,如要重新开启程序*/char ops[MAXSIZE]; //运算符栈int ops_top; //运算符栈顶标识double ovs[MAXSIZE]; //操作数栈int ovs_top; //操作数栈顶标识void push_ops(char x); //运算符进栈void push_ovs(double x); //操作数进栈char pop_ops(); //运算符出栈double pop_ovs();//操作数出栈char gettop_ops(); //取出运算符栈顶元素double gettop_ovs(); //取出操作数栈顶元素void inistack_ops(); //初始化运算符栈void inistack_ovs(); //初始化操作数栈char Precede(char t1,char t2); //判断t1与t2的优先级别int char_In(char c); //判断c是否为运算符double Operate(double a,char theta,double b); //对出栈的两个数计算double EvaluateExpression( );//使用算符优先算法进行算术表示式求值//ops[]为运算符栈,ovs[]为操作数栈int main(int argc, char* argv[]){double x;while(1) /*循环进行计算器*/{printf("请输入算术表达式,以回车结束\n");x=EvaluateExpression( );printf("通信0801李胜博的计算器\n答案=");if(ops_top!=0||ovs_top!=0){printf("error");}else{printf("%f\n",x);} /*如果栈内还有东西则输出错误*/ }}void push_ops(char x) //运算符进栈{if(ops_top==MAXSIZE-1){printf("运算符栈已满!上溢\n");exit(1);}else{ops_top++;ops[ops_top]=x;}}void push_ovs(double x) //操作数进栈{if(ovs_top==MAXSIZE-1){printf("操作数栈已满!上溢\n");exit(1);}else{ovs_top++;ovs[ovs_top]=x;}}char pop_ops() //运算符出栈{char y;if(ops_top==-1){printf("运算符栈空!下溢\n");exit(1);}else{y=ops[ops_top];ops_top--;}return y;}double pop_ovs() //操作数出栈{double y;if(ovs_top==-1){printf("操作数栈空!下溢\n");exit(1);}else{y=ovs[ovs_top];ovs_top--;}return y;}char gettop_ops() //取出运算符栈顶元素{if (ops_top!=-1)return ops[ops_top];else{printf("取数时运算符栈已空\n");exit(1);}}double gettop_ovs() //取出操作数栈顶元素{if (ovs_top!=-1)return ovs[ovs_top];else{printf("取数时操作数栈已空\n");exit(1);}}void inistack_ops() //初始化运算符栈{ops_top=-1;}void inistack_ovs() //初始化操作数栈{ovs_top=-1;}char Precede(char t1,char t2) //判断t1与t2的优先级别{char f;switch(t2){case '+':case '-':if (t1=='('||t1==END)f='<';elsef='>';break;case '*':case '/':if (t1=='('||t1=='-'||t1=='+'||t1==END)f='<';else f='>';break;case 'z':case 'f': /*符号的优先级高于加减乘除*/ if (t1=='f'||t1==')'||t1=='z')f='>';else f='<';break;case '^': /*优先级来参考卡西欧计算器*/if (t1==')'||t1=='f'||t1=='z'||t1=='!'||t1=='^')f='>';else f='<';break;case '!':if (t1==')'||t1=='f'||t1=='z'||t1=='!')f='>';else f='<';break;case '(':if (t1==')'){printf("运算符error1\n");exit(1);}elsef='<';break;case ')':switch(t1){case '(':f='=';break;case END:printf("运算符错误2\n");exit(1);default:f='>';}break;case END:switch(t1){case END:f='=';break;case '(':printf("运算符错误3\n");exit(1);default:f='>';}}return f;}int char_In(char c) //判断c是否为运算符{switch(c){case '+':case '-':case '*':case '/':case '(':case '^':case '!':case ')':case 'z':case 'f': /*定义了负数符号*/ case END:return 1;default :return 0;}}double Operate(double a,char theta,double b) //对出栈的两个数计算{ int i;double c;switch(theta) //theta为运算符{case '^': /*幂指数的算法么,能计算正负数的指数,不能计算分式的指数*/c=1;if(b>0){for(i=0;i<b;i++){c=c*a;}}else if(b==0){c=1;}else for(i=0;i>b;i--){c=c/a;}break;case '!': /*阶乘的算法*/ c=1;for(i=1;i<=b;i++){c=i*c;}break;case '+':c=a+b; //输出0-9的ASCII码break;case '-':c=a-b;break;case '*':c=a*b;break;case '/':c=a/b;break;}return c;}double EvaluateExpression( ){//使用算符优先算法进行算术表示式求值//ops[]为运算符栈,ovs[]为操作数栈double a,b,c,d,e,f,g,h,x,temp1,temp2,temp3,n;char stack_x,theta,input_c;int i=0;char str[100];inistack_ops(); //初始化运算符栈push_ops(END); //使结束符进栈inistack_ovs(); //初始化操作数栈while((str[i]=getchar())!='\n') /*字符串输入下面顺序输出(可以观察‘-’和其他字符的相对位置)*/{if(str[i]=='-'){ if(str[i-1]>='0'&&str[i-1]<='9'||str[i-1]==')'||str[i-1]=='!') ;else str[i]='f';} /*定义了一个“f”字符作为负号(同时设置优先级和判断字符)*/if(str[i]==')')if(str[i-1]=='(') str[i]='(';if(str[i]=='.') /*连续输入小数点时显示为错*/if(str[i-1]=='.') str[i]='x';if(str[i]=='^')if(str[i-1]=='.') str[i]='x';if(str[i]=='!')if(str[i-1]=='.') str[i]='x';if(str[i]=='+'){ if(str[i-1]>='0'&&str[i-1]<='9'||str[i-1]==')'||str[i-1]=='!') ; /*定义了一个“z”字符作为正号(同时设置优先级和判断字符)*/else str[i]='z';}i++;}if(i==1)str[i-1]='x'; /*单个字输入的时候显示错误*/str[i]='\n';i=0;input_c=str[i];i++;stack_x=gettop_ops();while(input_c!=END||stack_x!=END) //判断计算是否结束{if (char_In(input_c)) //若输入的字符是9种运算符之一{switch (Precede(stack_x,input_c)){case '<':push_ops(input_c); //若栈顶(x)优先级<输入则输入进栈input_c=str[i];i++;break;case '=':stack_x=pop_ops();//相等则出栈,即脱括号接受下一个字符input_c=str[i];i++;break;case '>':theta=pop_ops();if(theta=='f'){b=pop_ovs();b=0-b;push_ovs(b);}else if(theta=='z'){b=pop_ovs();b=0+b;push_ovs(b);}else if(theta=='!') /*阶乘计算时要另设一个a=1*/{a=1;b=pop_ovs();push_ovs(Operate(a,theta,b));}else{b=pop_ovs();a=pop_ovs();push_ovs(Operate(a,theta,b));}break;}}else if(input_c>='0'&&input_c<='9')//input_c是操作数{input_c=input_c-'0';push_ovs(input_c);input_c=str[i];i++;while(input_c>='0'&&input_c<='9'){ /*把连续输入的字符前面一位提出来*10+后面那位*/c=pop_ovs()*10;d=input_c-'0';e=c+d;push_ovs(e);input_c=str[i];i++;}}else if(input_c=='.') /*小数点后一位把最后输入那个数/10在相加返回到栈*/{input_c=str[i];i++;n=0;while(input_c>='0'&&input_c<='9'){n++;x=pow(10,n);f=pop_ovs();g=(double)(input_c-'0')/x;h=f+g;push_ovs(h);input_c=str[i];i++;}}else{printf("非法字符\n");exit(1);}stack_x=gettop_ops();}return(gettop_ovs());}/*还可以调用math.h,排完优先级之后把相应三角函数,开根号给编出来。
C语言编写的计算器源代码

C语言编写的计算器源代码```c#include<stdio.h>#include<stdlib.h>#include<string.h>#include<ctype.h>#define MAX_EXPRESSION_SIZE 100//栈结构定义typedef structint top;double data[MAX_EXPRESSION_SIZE];} Stack;//初始化栈void initStack(Stack *s)s->top = -1;//入栈void push(Stack *s, double value)if (s->top == MAX_EXPRESSION_SIZE - 1)printf("Stack is full. Cannot push element.\n");} elses->data[++(s->top)] = value;}//出栈double pop(Stack *s)if (s->top == -1)printf("Stack is empty. Cannot pop element.\n"); return -1;} elsereturn s->data[(s->top)--];}//获取栈顶元素double peek(Stack *s)if (s->top == -1)return -1;} elsereturn s->data[s->top];}//判断运算符的优先级int getPriority(char operator)switch (operator)case '+':case '-':return 1;case '*':case '/':return 2;case '^':return 3;default:return -1;}//执行四则运算double performOperation(double operand1, double operand2, char operator)switch (operator)case '+':return operand1 + operand2;case '-':return operand1 - operand2;case '*':return operand1 * operand2;case '/':if (operand2 != 0)return operand1 / operand2;} elseprintf("Error: Division by zero.\n");exit(1);}case '^':return pow(operand1, operand2);default:return 0;}//计算表达式结果double evaluateExpression(char *expression) Stack operandStack;Stack operatorStack;initStack(&operandStack);initStack(&operatorStack);int length = strlen(expression);for (int i = 0; i < length; i++)//忽略空格if (expression[i] == ' ')continue;}//数字直接入栈if (isdigit(expression[i]))double num = 0;while (i < length && (isdigit(expression[i]) , expression[i] == '.'))num = num * 10 + (expression[i] - '0');i++;}i--;push(&operandStack, num);}//左括号入栈else if (expression[i] == '(')push(&operatorStack, expression[i]);}//右括号出栈并执行运算,直到遇到左括号else if (expression[i] == ')')while (peek(&operatorStack) != '(')double operand2 = pop(&operandStack);double operand1 = pop(&operandStack);char operator = pop(&operatorStack);double result = performOperation(operand1, operand2, operator);push(&operandStack, result);}pop(&operatorStack);}//运算符出栈并执行运算,直到栈空或者遇到优先级较低的运算符elsewhile (peek(&operatorStack) != -1 &&getPriority(expression[i]) <= getPriority(peek(&operatorStack))) double operand2 = pop(&operandStack);double operand1 = pop(&operandStack);char operator = pop(&operatorStack);double result = performOperation(operand1, operand2, operator);push(&operandStack, result);}push(&operatorStack, expression[i]);}}//处理剩下的运算符while (peek(&operatorStack) != -1)double operand2 = pop(&operandStack);double operand1 = pop(&operandStack);char operator = pop(&operatorStack);double result = performOperation(operand1, operand2, operator);push(&operandStack, result);}return pop(&operandStack); // 返回最终结果int maichar expression[MAX_EXPRESSION_SIZE];printf("Enter an arithmetic expression: ");fgets(expression, MAX_EXPRESSION_SIZE, stdin);double result = evaluateExpression(expression);printf("Result = %.2f\n", result);return 0;```这个计算器可以实现基本的四则运算,支持括号和浮点数。
C语言计算器程序源代码

C语⾔计算器程序源代码//strcmp(s1,s2) 当s1⼤于s2时,返回1 ,s1⼩于s2时,返回-1,相等时,返回0 #include "stdio.h"#include "ctype.h"#include "string.h"#include "math.h"#define MAX 256#define STACK_SIZE 128#define WORD_LEN 8#define POP 1#define PUSH 0#define ERR -1#define END 2#define OPER 0#define NUM 1#define WORD 2#define ADD 1#define SUB 2#define MUL 3#define DIV 4#define POW 5#define FAC 6#define BRA_L 7#define BRA_R 8#define SIN 9#define COS 10#define TAN 11#define CTG 12#define LG 13 //以10为底的常⽤对数//#define LN 14//#define LOG 15//⾏标为当前操作符代号,列标为栈顶元素代号//2表⽰计算结束,0表⽰当前操作符进栈,1表⽰栈顶操作符出栈// \0 + - * / ^ ! ( ) sin cos tg ctg lgint Priority[14][14]={2, 1, 1, 1, 1, 1, 1,-1,-1, 1, 1, 1, 1, 1, /* \0 */0, 1, 1, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* + */0, 1, 1, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* - */0, 0, 0, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* * */0, 0, 0, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* / */0, 0, 0, 1, 1, 1, 1, 0,-1, 0, 0, 0, 0, 0, /* ^ */0, 0, 0, 0, 0, 0, 1, 0,-1, 0, 0, 0, 0, 0, /* ! */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* ( */-1,1, 1, 1, 1, 1, 1, 1,-1, 1, 1, 1, 1, 1, /* ) */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* sin */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* cos */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* tg */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* ctg */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0}; /* lg */char KeyWord[36][WORD_LEN+1]={"sin", //前12个为函数,多余的⽤于扩展"cos","tan","tg","ctg","lg","","","","","","","","","","help", // 后⾯为命令,多余的为扩展"version","set","digit", //精度,⼩数点后的位数"color","radian", //弧度"degree", //⾓度"file","clr","clear","window", //窗⼝模式"fullscr", //全屏模式"","","","","","","","",""};int OperCode(char c){int code;switch(c){case '\0':code=0;break;case '+':code=1;break;case '-':code=2;break;case '*':code=3;break;case '/':code=4;break;case '^':code=5;break;case '!':code=6;break;case '(':code=7;break;case ')':code=8;break;case 's':code=9;break; //sincase 'c':code=10;break; //coscase 't':code=11;break; //tgcase 'C':code=12;break; //ctgcase 'l':code=13;break; //log default:code=-1;break;};return code;}int WordCode(char* word){int i;for(i=0;i<25;i++)if(strcmp(KeyWord[i],word)==0) break;if(i>=25)return -1;else}void help(){printf("显⽰帮助信息!\n");return;}void version(){printf("显⽰版本信息!\n");return;}void Err(int errcode,int position,char *p){printf("\n ERR:%d Position:%d %s",errcode,position,p); return;}double long factorial(int i){if(i==1 || i==0)return(1.0);elsereturn(i*factorial(i-1));}main(){char Expression[MAX+1];int Operator[STACK_SIZE];int OperStackTop;double long Number[STACK_SIZE];int NumStackTop;double long NumList[STACK_SIZE];int NumCursor,NumListSize;int OperList[STACK_SIZE];int OperCursor,OperListSize;int WordList[STACK_SIZE];int WordCursor,WordListSize;int Index[MAX+1];int IndexCursor,IndexSize;char Word[WORD_LEN+1];double long num,num1,num2,weight,tempnum;int Oper;int isDecimal,isErr,isNumber,isEnd;char CurrentOper;int i,j,k,m,n;char ch;num=0.0;num2=0.0;tempnum=0.0;Oper=-1;while(1){for(i=0;i<=MAX;i++) //表达式初始化,中间表索引初始化{Expression[i]='\0';Index[i]=-1;}for(i=0;i{Operator[i]='0';Number[i]=0.0;NumList[i]=0.0;OperList[i]=-1;WordList[i]=-1;}NumStackTop=-1; //栈顶指针初始化OperStackTop=0; //操作符栈压⼊\0Operator[OperStackTop]=OperCode('\0');NumCursor=0; //各种中间表指针初始化,各种中间表的长度初始化NumListSize=0;OperCursor=0;OperListSize=0; //操作符表中先写⼊第⼀个操作符'\0'WordCursor=0;WordListSize=0;IndexCursor=0;IndexSize=0;// Index[0]=OPER;printf("Cal>"); //初始化完成,输出提⽰符i=0;while((ch=getchar())!='\n'){if(i>MAX) /*输⼊超长,则出错*/{Err(0,i,"输⼊的表达式长度超过规定值!\n");isErr=1;break;}if(isupper(ch))ch=tolower(ch);Expression[i]=ch;i++;}if(isErr==1){isErr=0;continue;}if(strlen(Expression)==0) //直接回车continue;if(strcmp("end",Expression)==0 ||strcmp("exit",Expression)==0 || strcmp("quit",Expr ession)==0)break;//⼀下代码为编译预处理,主要处理负号,并检查括号是否配对k=0;for(i=0;Expression[i]!='\0';i++){if((i==0&&Expression[i]=='-') || (i>0&&Expression[i]=='-'&&Expression[i-1]=='(')){for(j=strlen(Expression);j>i;j--)Expression[j]=Expression[j-1];Expression[i]='0';}if(Expression[i]=='(') //检查括号k++;if(Expression[i]==')')k--;}if(k>0) //如果括号不配对{Err(1,-1,"缺少右括号 )\n");continue;}if(k<0){Err(1,-1,"缺少左括号 (\n");continue;}//编译预处理结束i=0; //词法分析while(1){if(Expression[i]=='\0'){OperList[OperListSize]=OperCode(Expression[i]);OperListSize++;Index[IndexSize]=OPER;IndexSize++;// printf("IndexSize=%d,Index[IndexSize]=%d,Expression[i]=%c\n",IndexSize,Index[IndexSize],Expression[i]); break;}isDecimal=0;isNumber=0;while(isdigit(Expression[i])||Expression[i]=='.') //读取数字{isNumber=1;if(Expression[i]=='.'){if((i<(MAX-1) && !isdigit(Expression[i+1])) || (i+1)==MAX) //不正确的⼩数点位置{Err(2,i,"⼩数点位置不正确!\n");isErr=1;isNumber=0;i++;break;}isDecimal=1;weight=0.1;i++;continue;}if(isDecimal==0)num=num*10.0+(double long)(Expression[i]-'0');{num=num+(double long)(Expression[i]-'0')*weight;weight=weight*0.1;}i++;} //数字读完if(isErr==1)break;if(isNumber==1) //如果刚才成功读取了数字,则数字⼊栈{NumList[NumListSize]=num;NumListSize++;isNumber=0;num=0.0;Index[IndexSize]=NUM;// printf("IndexSize=%d,Index[IndexSize]=%d\n",IndexSize,Index[IndexSize]); IndexSize++;}for(k=0;k<=WORD_LEN;k++)Word[k]='\0';j=0;while(isalpha(Expression[i])){if(j>=WORD_LEN) //超过长度仍然未匹配,则出错{Err(3,i,"单词长度超过规定值/未定义的单词:");printf("%s\n",Word);isErr=1;break;}Word[j]=Expression[i];j++;// printf("WORD:%s\n",Word);if(WordCode(Word)==-1) //匹配不成功{if(!isalpha(Expression[i+1]))//匹配不成功,但是下⼀个字符已经不是字母,{Err(4,i,"未定义的单词:"); //则出错,并跳出循环printf("%s\n",Word);isErr=1;break;} //匹配不成功且还能继续读取字符,则继续读取下⼀个字母i++;continue;}else //匹配成功,则单词⼊表,读取下⼀个字符{switch(WordCode(Word)){case 0:ch='s';break;case 1:ch='c';break;case 2:case 3:ch='t';break;case 4:ch='C';case 5:ch='l';break;default:ch='\0';WordList[WordListSize]=WordCode(Word);WordListSize++;Index[IndexSize]=WORD;IndexSize++;break;};if(ch!='\0'){OperList[OperListSize]=OperCode(ch);OperListSize++;Index[IndexSize]=OPER;IndexSize++;}i++;break;}} //单词读完if(isErr==1)break;if(Expression[i]==' ')i++;if(!isdigit(Expression[i]) && !isalpha(Expression[i]) && Expression[i]!='\0') {if(OperCode(Expression[i])==-1){isErr=1;Err(5,i,"未定义的操作符:");printf("%c\n",Expression[i]);break;}else{OperList[OperListSize]=OperCode(Expression[i]);OperListSize++;Index[IndexSize]=OPER;IndexSize++;i++;}} //操作符读完if(isErr==1)break;} //词法分析结束if(isErr==1){isErr=0;continue;}/* for(k=0;kprintf("NumList[%d]=%f\n",k,NumList[k]);for(k=0;kprintf("OperList[%d]=%d\n",k,OperList[k]);for(k=0;kprintf("WordList[%d]=%d\n",k,WordList[k]);for(k=0;kprintf("Index[%d]=%d\n",k,Index[k]);printf("\n\n IndexCursor=%d IndexSize=%d,\n",IndexCursor,IndexSize);printf("OperStacktop=%d,Operator[OperStackTop]=%d,NumStackTop=%d\n",OperStackTop,Operator[OperStackTop],NumStackTop); // continue;*/isEnd=0;IndexCursor=0;while(1){if(Index[IndexCursor]==NUM){if(NumCursor<0 || NumListSize<0){Err(10,-1,"索引列表与操作数列表信息不匹配\n");isErr=1;break;}NumStackTop++;Number[NumStackTop]=NumList[NumCursor];NumCursor++;IndexCursor++;continue;} //数字处理if(Index[IndexCursor]==OPER){m=OperList[OperCursor];n=Operator[OperStackTop];switch(Priority[m][n]){case ERR:Err(20,IndexCursor,"不可预见的错误!\n");isErr=1;break;case PUSH:OperStackTop++;Operator[OperStackTop]=m;OperCursor++;IndexCursor++;break;case END:isEnd=1;break;case POP:Oper=Operator[OperStackTop];OperStackTop--;switch(Oper){case BRA_L: IndexCursor++;OperCursor++;break;case ADD:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;num1=Number[NumStackTop];NumStackTop--;tempnum=num1+num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(11,IndexCursor,"加法运算缺少操作数!\n");isErr=1;}break;case SUB:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;num1=Number[NumStackTop];NumStackTop--;tempnum=num1-num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(12,IndexCursor,"减法运算缺少操作数!\n");isErr=1;}break;case MUL:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;num1=Number[NumStackTop];NumStackTop--;tempnum=num1*num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(13,IndexCursor,"乘法运算缺少操作数!\n");isErr=1;}break;case DIV:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;if(num2==0.0){Err(14,IndexCursor,"除数为 0 ,不能进⾏除法运算!\n"); isErr=1;break;}num1=Number[NumStackTop];NumStackTop--;tempnum=num1/num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(15,IndexCursor,"除法运算缺少操作数!\n"); isErr=1;}break;case POW:if(NumStackTop>=1){num2=Number[NumStackTop]; NumStackTop--;num1=Number[NumStackTop]; NumStackTop--;tempnum=pow(num1,num2); NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(16,IndexCursor,"乘⽅运算缺少操作数!\n"); isErr=1;}break;case FAC:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=factorial(num2); NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(17,IndexCursor,"阶乘运算缺少操作数!\n"); isErr=1;}break;case SIN:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=sin(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}{Err(18,IndexCursor,"正弦函数缺少参数!\n"); isErr=1;}break;case COS:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=cos(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(19,IndexCursor,"余弦函数缺少参数!\n"); isErr=1;}break;case TAN:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=tan(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(20,IndexCursor,"正切函数缺少参数!\n");isErr=1;}break;case CTG:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=1.0/tan(num2); NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(21,IndexCursor,"余切函数缺少参数!\n"); isErr=1;}break;/* case LN:if(NumStackTop>=0)num2=Number[NumStackTop]; NumStackTop--;if(num2<=0.0){Err(20,IndexCursor,"⾃然对数函数真数:"); printf(" %f ⼩于0!\n",num2);isErr=1;break;}tempnum=log(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(17,IndexCursor,"⾃然对数函数缺少参数!\n"); isErr=1;}break; */case LG:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;if(num2<=0.0){Err(23,IndexCursor,"常⽤对数函数真数:"); printf(" %f ⼩于0!\n",num2);isErr=1;break;}tempnum=log10(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(22,IndexCursor,"常⽤对数函数缺少参数!\n"); isErr=1;}break;default:Err(100,IndexCursor,"运算符(代码:"); printf(" %d )暂不⽀持!\n",Oper);isErr=1;break;/*#define SIN 9#define COS 10#define TAN 11#define CTG 12#define LOG 13 */}; //switch 语句结束break;};//switchif(isErr==1 || isEnd==1)break;continue;} //运算符处理if(Index[IndexCursor]==WORD){printf(" 单词尚未处理!\n");break;}//在这⾥处理单词}//核⼼计算结束if(isErr==1){isErr=0;continue;}if(NumStackTop>0){Err(1000,-1,"多余的操作数:");printf("%f!\n",Number[NumStackTop]);}elseif(NumStackTop==0 && isEnd==1){if(fabs(Number[NumStackTop])>1e20) printf(" %.20e\n",Number[NumStackTop]); elseprintf(" %f\n",Number[NumStackTop]); isEnd=0;}}//主循环结束}//主函数结束。
c语言编写的计算器代码附带使用说明

#include<stdio.h>#include<math.h>void main(){double a,b,j;char x1,x2,x3,x4,x;printf("请选择所求公式区域A,B,C!\n\a"); x=getchar();switch(x){ case 'A':{ printf("请输入具体公式!\n");scanf("%lf%c%lf",&a,&x1,&b);if(x1==43){j=a+b;printf("和=%.2lf\n\n",j);}else if(x1==45){j=a-b;printf("差=%.2lf\n",j);}else if(x1==42){j=a*b;printf("积=%.2lf\n",j);}else if(x1==47){j=a/b;printf("商=%.2lf\n",j);}else if(x1==37){int(j)=int(a)%int(b);printf("%.2lf对%.2lf的余数=%d\n",a,b,j);}else if(x1==112){j=pow(a,b);printf("%.0lf的%.0lf次方=%.0lf\n",a,b,j);}else printf("输入有误,请按要求输入!\n\a\a\a");printf("谢谢使用!\n\n");break;}case 'B':{ printf("请输入具体公式!\n");getchar();scanf("%c%c%c%lf",&x1,&x2,&x3,&a);if(x1=='l'&&x2=='e'&&x3=='n'){j=log(a);printf("len(%.2lf)=%.2lf\n",a,j);}else if(x1=='l'&&x2=='o'&&x3=='g'){j=log10(a);printf("以10为底%.2lf的对数=%.2lf\n",a,j);}else if(x1=='s'){j=sin(a);printf("sin%.4lf=%.5lf\n",a,j);}else if(x1=='c'){j=cos(a);printf("cos%.4lf=%.5lf\n",a,j);}else if(x1=='t'){j=tan(a);printf("tan%.4lf=%.5lf\n",a,j);}else printf("输入有误,请按要求输入!\n\a\a\a");printf("谢谢使用!\n\n");break;}case 'C':{printf("请输入具体公式!\n");getchar();scanf("%c%c%c%c%lf",&x1,&x2,&x3,&x4,&a); if(x1=='s'&&x2=='q'&&x3=='r'&&x4=='t'){j=sqrt(a);printf("根号a=%.2lf\n",j);}else if(x1=='f'&&x2=='a'&&x3=='b'&&x4=='s') {j=fabs(a);printf("%.2lf的绝对值=%.2lf\n",a,j);}else if(x1=='a'&&x2=='c'&&x3=='o'&&x4=='s') {j=acos(a);printf("cos-1(%.2lf)=%.4lf\n",a,j);}else if(x1=='a'&&x2=='s'&&x3=='i'&&x4=='n') {j=asin(a);printf("sin-1(%.2lf)=%.4lf\n",a,j);}else if(x1=='a'&&x2=='t'&&x3=='a'&&x4=='n') {j=atan(a);printf("tan-1(%.2lf)=%.4lf\n",a,j);}else if(x1=='t'&&x2=='a'&&x3=='n'&&x4=='h'){j=tanh(a);printf("%.2lf的双曲正切函数=%.4lf\n",a,j);}else if(x1=='s'&&x2=='i'&&x3=='n'&&x4=='h'){j=sinh(a);printf("%.2lf的双曲正弦函数=%.4lf\n",a,j);}else if(x1=='c'&&x2=='o'&&x3=='s'&&x4=='h'){j=cosh(a);printf("%.2lf的双曲余弦函数=%.4lf\n",a,j);}else printf("输入有误,请按要求输入!\n\a\a\a");printf("谢谢使用!\n\n");break;}}}使用说明该软件分为3个板块,计算前请先输入一个板块号码,如A,B,C !各板块包含以下公式:A :(包含加、减、乘、除、求平方、求余数)B:(包含len 、a 10log 、 sin 、cos 、tan )C:(包含求根号、绝对值、cos ,sin ,tan 的反函数、a 的双曲正切、正弦、余弦函数)。
计算器C语言代码

printf("\t*——使用方法: *\n");
printf("\t* 请选择输入下列功能前的数字序号后按enter键进入。 *\n");
if(ch=='+'||ch=='-')
{
ch=Srcexp[++i];
flg=1;
}
}
if (isdigit(ch))
{
val=ch-'0';
while (isdigit(ch=Srcexp[++i]))
{
val=val*10.0+ch-'0';
case iSUB: op2=iPop();
else if(op2=='3')
p();
else if(op2=='4')
{
printf(" ********************谢谢使用********************\n");
exit(0);
}
else if(op2!='1' || op2!='2' || op2!='3' || op2!='4' )
if(op2=='Y' || op2=='y')
getchar();
W:scanf("%c",&op2);
getchar();
c语言计算器源代码

# include <stdio.h># include <malloc.h># include <conio.h># define maxsize 100typedef double datatype1;typedef char datatype2;typedef struct stack1{datatype1 data1[maxsize];int top1; /*栈顶元素*/}seqstack1,*pseqstack1; /*顺序栈*/typedef struct stack2{datatype2 data2[maxsize];int top2; /*栈顶元素*/}seqstack2,*pseqstack2; /*顺序栈*//*栈的初始化*/pseqstack1 init_seqstack1(void){pseqstack1 S;S=(pseqstack1)malloc(sizeof(pseqstack1)); if(S)S->top1=-1;return S;}pseqstack2 init_seqstack2(void){pseqstack2 S;S=(pseqstack2)malloc(sizeof(pseqstack2)); if(S)S->top2=-1;return S;}/*判断栈空*/int empty_seqstack1(pseqstack1 S){if(S->top1==-1)return 1;elsereturn 0;}int empty_seqstack2(pseqstack2 S){if(S->top2==-1)return 1;elsereturn 0;}/*X入栈*/int push_seqstack1(pseqstack1 S,datatype1 X) {if(S->top1==maxsize-1){printf("栈满,无法入栈!\n");return 0;}else{S->top1++;S->data1[S->top1]=X;return 1;}}int push_seqstack2(pseqstack2 S,datatype2 X) {if(S->top2==maxsize-1){printf("栈满,无法入栈!\n");return 0;}else{S->top2++;S->data2[S->top2]=X;return 1;}}/*X出栈*/int pop_seqstack1(pseqstack1 S,datatype1 *X) {if(empty_seqstack1(S))return 0;else{*X=S->data1[S->top1];S->top1--;return 1;}}int pop_seqstack2(pseqstack2 S,datatype2 *X) {if(empty_seqstack2(S))return 0;else{*X=S->data2[S->top2];S->top2--;return 1;}}/*求栈顶元素*/int gettop_seqstack1(pseqstack1 S,datatype1 *X){if(empty_seqstack1(S))return 0;else*X=S->data1[S->top1];return 1;}int gettop_seqstack2(pseqstack2 S,datatype2 *X){if(empty_seqstack2(S))return 0;else*X=S->data2[S->top2];return 1;}/*判断字符是否为操作数。
C语言简单计算器程序源代码

C语言简单计算器程序源代码以下是一个简单的C语言计算器程序的源代码:```c#include <stdio.h>int maichar operator;double num1, num2;printf("请输入运算符:");scanf("%c", &operator);printf("请输入两个数字:");scanf("%lf %lf", &num1, &num2);switch (operator)case '+':printf("%.2lf + %.2lf = %.2lf", num1, num2, num1 + num2); break;case '-':printf("%.2lf - %.2lf = %.2lf", num1, num2, num1 - num2); break;case '*':printf("%.2lf * %.2lf = %.2lf", num1, num2, num1 * num2);break;case '/':if (num2 != 0)printf("%.2lf / %.2lf = %.2lf", num1, num2, num1 / num2);elseprintf("除数不能为0");break;default:printf("无效的运算符");}return 0;```这个程序首先提示用户输入一个运算符,然后再提示输入两个数字。
接下来,程序会根据输入的运算符执行相应的计算,并打印结果。
在计算除法时,程序会检查除数是否为0,如果为0,则打印错误信息。
请注意,这只是一个非常简单的计算器程序,没有考虑很多错误处理情况。
C语言计算器源代码

C++语言编写。
#include<iostream>#include<cmath>#include<string>using namespace std;const int SIZE = 1000;typedef struct node//为了处理符号而建立的链表(如: 1+(-2)) {char data;node *next;}node;typedef struct stack_num//存储数的栈{double *top;double *base;}stack_num;typedef struct stack_char//存储运算符号的栈{char *top;char *base;}stack_char;stack_num S_num;//定义stack_char S_char;//定义char fu[18] = {'\n', ')', '+', '-', '*', '/', '%', '^','Q', 'L', 'C', 'S', 'T', 'c', 's', 't', '('};int compare[1000];//表现出各运算符号的优先级double shu[1000];//存储 "数" 的数组double dai_result;//运算的结果,是为了处理 M 运算(简介函数里有M的定义)int biao = 0;//和dia_result 一样,为了处理 M 运算char line[SIZE];//输入的所要计算的表达式void init()//初始化{compare[fu[0]] = -2;//用数字的大小表现出符号的优先级compare[fu[1]] = -1;compare[fu[2]] = 2;compare[fu[3]] = 2;compare[fu[4]] = 4;compare[fu[5]] = 4;compare[fu[6]] = 4;compare[fu[7]] = 5;for(int i = 8; i <= 15; i++)compare[fu[i]] = 6;compare[fu[16]] = 7;S_num.base = (double*)malloc(sizeof(double)*SIZE);//为栈开辟空间S_char.base = (char*)malloc(sizeof(char)*SIZE);//同上S_num.top = S_num.base;S_char.top = S_char.base;}void push_num(double n)//数字进栈{* ++S_num.top = n;}void push_char(char c)//运算符号进栈{* ++S_char.top = c;}double pop_num()//数字出栈{double m = *S_num.top;S_num.top--;return m;}char pop_char()//运算符号出栈{char cc = *S_char.top;S_char.top--;return cc;}char get_top_char()//得到运算符号的栈中最顶端的运算符号{return *S_char.top;}double operate(double y, char c, double x)//对两个数计算(含是双目运算符:如 *, / 等等){double r;if(c == '-')r = x - y;else if(c == '+')r = x + y;else if(c == '/' && y != 0)r = x / y;else if(c == '*')r = x * y;else if(c == '^'){r = 1;for(int i = 1; i <= y; i++)r *= x;}else if(c == '%'){int r0 = (int)x % (int)y;r = double(r0);}return r;}double operate_one(double one, char cc)//对一个数运算(含单目运算符:如log(L), sin(S) 等等){double r;if(cc == 'Q')r = sqrt(one);else if(cc == 'C')r = cos(one);else if(cc == 'S')r = sin(one);else if(cc == 'T')r = tan(one);else if(cc == 'c')r = acos(one);else if(cc == 's')r = asin(one);else if(cc == 't')r = atan(one);return r;}double operate_L(double a, double b, char dian)//求对数的值{double r = log(b) / log(a);return r;}double compute()//对整个表达式的计算{char c;//表示运算符号int p = 0;//用于shu[++p], 先初始化int i, j;init();//进行初始化push_char('\n');line[strlen(line)] = '\n';line[strlen(line)+1] = '\0';if(biao)push_num(dai_result);//把运算的结果先进栈, 在这个结果的基础上继续进行运算biao = 0;for(i = 0; line[i] != '\0';)//把表达式中的数字字符串转化成可计算的数字{int flag = 0;int flag1 = 1;//标记是否是运算符号// int flag2 = 1;//标记是否出现'_';double h = 0;int ge;//位数int biao_dian = 0;//是否是小数的类型while(1){flag1 = 1;for(j = 0; j <= 16; j++){if(line[i] == fu[j]){flag1 = 0;break;}}if(line[i] == '_') {break;}if(line[i] == '.') {i++;ge = 0;biao_dian = 1; }if(line[i] == 'P') {shu[++p] = pi;i++;break;}if(line[i] == 'E') {shu[++p] = e;i++;break;}if(flag1){h = h * 10 + (line[i] - '0');flag = 1;i++;if(biao_dian)ge++;}elsebreak;}if(flag){if(biao_dian){int r = 1;for(int k = 1; k <= ge; k++)r *= 10;h /= r;}shu[++p] = h;//把转化而来的数字存于数组}if(line[i] == '+')shu[++p] = -1;else if(line[i] == '-')shu[++p] = -2;else if(line[i] == '*')shu[++p] = -3;else if(line[i] == '/')shu[++p] = -4;else if(line[i] == '%')shu[++p] = -5;else if(line[i] == '^')shu[++p] = -6;else if(line[i] == 'Q')shu[++p] = -7;else if(line[i] == 'L')shu[++p] = -8;else if(line[i] == 'C')shu[++p] = -9;else if(line[i] == 'S')shu[++p] = -10;else if(line[i] == 'T')shu[++p] = -11;else if(line[i] == 'c')shu[++p] = -12;else if(line[i] == 's')shu[++p] = -13;else if(line[i] == 't')shu[++p] = -14;else if(line[i] == '(')shu[++p] = -15;else if(line[i] == ')')shu[++p] = -16;else if(line[i] == '\n')shu[++p] = -17;i++;}i = 1;while(shu[i] != -17 || get_top_char() != '\n') {double m = shu[i];if(m >= 0){push_num(m);i++;}else{if(m == -1)c = '+';else if(m == -2)c = '-';else if(m == -3)c = '*';else if(m == -4)c = '/';else if(m == -5)c = '%';else if(m == -6)c = '^';else if(m == -7)c = 'Q';else if(m == -8)c = 'L';else if(m == -9)c = 'C';else if(m == -10)c = 'S';else if(m == -11)c = 'T';else if(m == -12)c = 'c';else if(m == -13)c = 's';else if(m == -14)c = 't';else if(m == -15)c = '(';else if(m == -16)c = ')';else if(m == -17)c = '\n';char ch = get_top_char();//得到最顶端运算符号if(compare[ch] < compare[c])//运算符号级别的比较{push_char(c);i++;}else if(ch == '(' && c == ')'){pop_char();i++;}else if(compare[ch] >= compare[c] && ch != '(' && ch != '\n') {if(ch == 'Q' || ch == 'C' || ch == 'S'|| ch == 'T' || ch == 'c' || ch == 's' || ch == 't'){double one = pop_num();char dian = pop_char();push_num(operate_one(one, dian));}else if(ch == 'L'){double one_L = pop_num();double two_L = pop_num();char dian = pop_char();push_num(operate_L(two_L, one_L, dian));}else{double x = pop_num();double y = pop_num();char dian = pop_char();if(dian == '/' && x == 0)//判断是否除了"零"{cout<<"由于您除了零,结果将是错误的"<<endl;}push_num(operate(x, dian, y));//把进行一次计算的结果入栈}}else{push_char(c);i++;}}}double result = pop_num();//得到结果return result;}int check_kuohao()//检查表达式括号是否匹配{int i, f = 0;int kuo[SIZE], key = 1;memset(kuo, 0, sizeof(kuo));for(i = 0; line[i] != '\0'; i++){if(line[i] == '(')kuo[++f] = 1;else if(line[i] == ')'){if(kuo[f] == 1){kuo[f] = 0;f--;}else{key = 0;break;}}}if(key && f == 0)return 1;elsereturn 0;}int check_char()//检查运算符号是否合法(如: 1 +* 4){int i, ge;for(i = 0; line[i] != '\0'; ){ge = 0;while(line[i] == '+' || line[i] == '-' || line[i] == '*' || line[i] == '/' || line[i] == '%' || line[i] == '^'|| line[i] == 'Q' || line[i] == 'L' || line[i] == 'S'|| line[i] == 'C' || line[i] == 'T' || line[i] == 's'|| line[i] == 'c' || line[i] == 't'){ge++;i++;}i++;}if(ge >= 3)return 0;elsereturn 1;}void output(double result)//打出结果{printf("所得结果是: ");cout<<result<<endl;}void check()//检查表达式是否合法{void introduce();char cc;//决定计算器按哪种功能进行计算double result;//结果void input();//定义if( check_kuohao() && check_char() )//看是否合法, 合法则计算{result = compute();output(result);cout<<"输入一个字符'M'或'D'或'F', 决定是否继续: "<<endl;while(cin>>cc){if(cc == 'M'){system("cls");introduce();printf("您上次所得结果为: ");cout<<result<<endl;cout<<"在上次计算结果的基础上, 请继续输入想计算的表达式"<<endl;dai_result = result;biao = 1;input();//输入表达式break;}else if(cc == 'D'){system("cls");introduce();cout<<"计算器已清零, 请输入您所要计算的表达式"<<endl;input();//输入表达式break;}else if(cc == 'F'){system("cls");cout<<"计算器关闭, 谢谢使用!"<<endl;break;}else{cout<<"所输入字符无效, 请输入一个字符'M'或'D'或'F'!"<<endl;continue;}}}else//不合法,分两种不合法{if(check_kuohao() == 0 && check_char() == 1){cout<<"您所输入的表达式括号不匹配, 请重新输入:"<<endl;input();//输入表达式}else{cout<<"您所输入的表达式不合法, 请重新输入:"<<endl;input();//输入表达式}}}void tackle_fuhao()//处理负号{node *root, *head, *p, *q, *p1;root = head = new node;head->next = NULL;int i;for(i = 0; line[i] != '\0'; i++)//建立链表{p = new node;p->data = line[i];p->next = head->next;head->next = p;head = p;}// delete p;q = (node*)malloc(sizeof(node));head = root;if(root->next->data == '+' || root->next->data == '-')//处理第一个字符{p = new node;p->data = '0';p->next = head->next;head->next = p;}if(root->next != NULL){for(q = root->next; q; q = q->next){if(q->data == '(' && (q->next->data == '-' || q->next->data == '+')){p = new node;p->data = '0';p->next = q->next;q->next = p;}}}// delete q;p1 = new node;int qi = -1;for(p1 = root->next; p1; p1 = p1->next){line[++qi] = p1->data;}line[++qi] = '\0';}void input()//输入{cin>>line;if(biao == 0)tackle_fuhao();//处理负号check();//检查表达式是否合法}void introduce()//对计算器的符号功能的简要介绍{cout<<"计算器简要介绍"<<endl;cout<<"C(cos) S(sin) T(tan) a(arccos) c(arcsin) "<<endl;cout<<"7 8 9 / on t(arctan) "<<endl;cout<<"4 5 6 * % L(log)"<<endl;cout<<"1 2 3 - M(M+) Q(sqrt) "<<endl;cout<<"0 . + ^(乘方) F(off) Enter(=) "<<endl;cout<<"对于对数输入 L2_5 表示以2为底5的对数"<<endl;cout<<"M(在前面结果的基础上继续计算,如:上次结果为10,现输入+10.5*2)"<<endl;cout<<"D(清零并继续输入)"<<endl;cout<<"F(计算机关闭)"<<endl;cout<<"输入P 就代表输入圆周率, 输入 E 代表输入自然对数"<<endl<<endl;}void print(){system("color 2");cout<<" 欢迎使用本计算器"<<endl;cout<<"输入一个字符串 on, 计算器开始启动"<<endl;}void if_start()//是否启动计算器{string start;print();while(cin>>start){if(start != "on"){cout<<"您所输入的字符无效, 请按照介绍的继续输入:"<<endl;continue;}elsebreak;}if(start == "on"){system("color 5");//颜色的处理system("cls");//刷屏}introduce();//对计算器的简要介绍cout<<"现在,请输入您所要计算的表达式"<<endl;input();//输入所要计算的表达式}int main(){if_start();//调用是否启动计算器函数return 0;}。
C语言 计算器 源代码

rectangle(25,25,375,75); /*画屏显的边框*/
setcolor(GREEN); /*设置绿色模式*/
settextstyle(0,0,3); /*改变字符大小方向函数*/
if (error) {strcpy(scr_main,"error"); setcolor(RED); Flag=0; Num_flag=0; clrnum(0,1); }
inregs.x.ax=0x01; /*显示鼠标*/
int86(0x33,&inregs,&outregs); /*通用软中断库函数*/
}
/*鼠标消息*/
int mouse_message()
{
drawmouse(&Mx,&My,&Mkey); /*调用画鼠标函数*/
for (;Mk0==Mkey;)
initgraph( &GraphDriver, &GraphMode, "" ); /*初始化图形系统*/
ErrorCode = graphresult(); /*读初始化结果*/
if( ErrorCode != grOk ) /*如果初始化时出现错误*/
{
void calculator(int fun_code); /*实现计算器功能函数声明*/
void clrnum(int n0,int n1); /*清空Num数组函数声明*/
void adv(void); /*高级函数功能声明*/
double qiu_zhi(char *bds_start,char *bds_end); /*求表达式值函数声明*/
C语言计算器源代码

C++语言编写;; include<iostream>include<cmath>include<string>using namespace std;const double pi = 3.;const double e = ;const int SIZE = 1000; typedef struct node{i++;ge = 0;biao_dian = 1;}iflinei == 'P'{shu++p = pi;i++;break;}iflinei == 'E'{shu++p = e;i++;break;}ifflag1{h = h 10 + linei - '0';flag = 1;i++;ifbiao_diange++;}elsebreak;}ifflag{ifbiao_dian{int r = 1;forint k = 1; k <= ge; k++r = 10;h /= r;}shu++p = h; + ^乘方 Foff Enter= "<<endl; cout<<"对于对数输入 L2_5 表示以2为底5的对数"<<endl;cout<<"M在前面结果的基础上继续计算,如:上次结果为10,现输入+2"<<endl;cout<<"D清零并继续输入"<<endl;cout<<"F计算机关闭"<<endl;cout<<"输入 P 就代表输入圆周率, 输入 E 代表输入自然对数"<<endl<<endl; }void print{system"color 2";cout<<" 欢迎使用本计算器"<<endl;cout<<"输入一个字符串 on, 计算器开始启动"<<endl;}void if_start//是否启动计算器{string start;print;whilecin>>start{ifstart = "on"{cout<<"您所输入的字符无效, 请按照介绍的继续输入:"<<endl;continue;}elsebreak;}ifstart == "on"{system"color 5";//颜色的处理system"cls";//刷屏}introduce;//对计算器的简要介绍cout<<"现在,请输入您所要计算的表达式"<<endl;input;//输入所要计算的表达式}int main{if_start;//调用是否启动计算器函数return 0;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include <stdio.h>
#include <math.h>
#include <string.h>
typedef struct Expression//定义表达式结构体
{
int num[64];
char ch[64];
}Exper;
typedef struct node //定义字栈
{
char e[100];
int top;
}linkstack;
typedef struct Node //定义整数栈
{
int c[100];
int top;
}link;
char precede(char a,char b) //符号判断
{
int i=0,j=0;
char sign[]="+-*/()^%";
char
prec[8][8]={">><<()<<",">><<()<<",">>>>()<<",">>>>()<<","((((~~((","))))~~))",">>>>()>>",">>>>()> >"};
if (b=='=')
{
return 0;
}
while(sign[i]!=a)
{
i++;
}
while (sign[j]!=b)
{
j++;
}
return(prec[i][j]);
}
void push1(linkstack *p,char c) //字符入栈
{
p->e[p->top++]=c;
}
void push2(link *p,int num) //整数入栈
{
p->c[p->top++]=num;
}
char gettop(linkstack *s) //读字符栈顶的元素{
char c;
c=s->e[s->top-1];
return(c);
}
char pop1(linkstack *s) //字符出栈{char c;
c=s->e[--s->top];
return(c);
}
int pop2(link *N) //整数入栈
{
int num;
num=N->c[--N->top];
return(num);
}
int operate(int a, char oper,int b)//进行运算
{
int num;
switch (oper)
{
case '+': num=a+b;break;
case '-': num=a-b;break;
case '*': num=a*b;break;
case '/': num=a/b;break;
case '^': num=pow(a,b);break;
case '%': num=a%b;break;
}
return num;
}
Exper number(char *n_w) //把输入的字符转换成整数和字符,并分别存在数组中
{
int i=0;
int j=0;
int k=0;
int temp;
Exper n_exper;
while (n_w[i]!='\0')
{
if (n_w[i]>='0'&& n_w[i]<='9')
{
temp=n_w[i]-'0';
i++;
while (n_w[i]>='0'&& n_w[i]<='9')
{
temp=temp*10+n_w[i]-'0';
i++;
}
n_exper.num[j]=temp;
j++;
}
n_exper.ch[k]=n_w[i];
k++;
i++;
}
return n_exper;
}
void Calculate(Exper C_exper)//计算函数
{
int i=0,j=0,k=1;
int br=0;
int temp1,temp2;//临时变量
char dec,CH;
linkstack cha;//定义字符栈
link Num;//定义整数栈
Num.top=0;
cha.top=0;
push1(&cha,'#');
do
{
if (j==0 && C_exper.ch[j]=='(')
{
br++;
}
if (C_exper.ch[j]!='=')
{
if (k==1)
{
push1(&cha,C_exper.ch[j]);
push2(&Num,C_exper.num[i]);
push2(&Num,C_exper.num[++i]);
dec=precede(gettop(&cha),C_exper.ch[++j]);
}
else
{
dec=precede(gettop(&cha),C_exper.ch[j]);
}
}
else
{
temp1=pop2(&Num);
temp2=pop2(&Num);
push2(&Num,operate(temp2,pop1(&cha),temp1));
printf("%d\n\n",pop2(&Num));
break;
}
switch(dec)
{
case '<':
{
push1(&cha,C_exper.ch[j]);
push2(&Num,operate(pop2(&Num),pop1(&cha),C_exper.num[++i]));
j++;
k++;
break;
}
case '>':
{
temp1=pop2(&Num);
temp2=pop2(&Num);
push2(&Num,operate(temp2,pop1(&cha),temp1));
push1(&cha,C_exper.ch[j]);
push2(&Num,C_exper.num[++i]);
j++;
k++;
break;
}
case '(':
{
if (br==1)
{
push1(&cha,C_exper.ch[j]);
br++;
j++;
k++;
i++;
}
else
{
push1(&cha,C_exper.ch[j]);
push1(&cha,C_exper.ch[++j]);
push2(&Num,C_exper.num[++i]);
j++;
k++;
}
break;
}
case ')':
{
push1(&cha,C_exper.ch[j]);
CH=pop1(&cha);
CH=pop1(&cha);
temp1=pop2(&Num);
temp2=pop2(&Num);
push2(&Num,operate(temp2,CH,temp1));
CH=pop1(&cha);
j++;
k++;
if (gettop(&cha)=='#')
{
push1(&cha,C_exper.ch[j]);
push2(&Num,C_exper.num[i]);
j++;
}
break;
}
default: break;
}
}while (gettop(&cha)!='#');
}
int main()
{
char w[128];
Exper m_exper;
printf("请输入表达式:\n");
scanf("%s",w);
printf("\n%s",w);
m_exper=number(w);
Calculate(m_exper);
getchar();
return 0;
}。