C语言计算器程序源代码
计算器课程设计c语言源程序
printf("\n");
for(i=0;i<5;i++) //第5行
printf(" ");
printf(" ");
for(i=0;i<=4;i++)
printf("\x02");
for(i=0;i<=10;i++)
for(i=0;i<3;i++)
printf(" ");
for(i=0;i<=5;i++)
printf("\x02 ");
printf("\n");
for(i=0;i<=3;i++) //第四行
printf("\x02 ");
for(i=0;i<7;i++)
printf(" ");
for(i=0;i<=4;i++)
printf("\x02");
printf("\n");
for(i=0;i<5;i++) //第6行
printf(" ");
printf("\b");
printf("\x02");
for(i=0;i<=22;i++)
if((i+1)%8==0)
printf("\n ");
计算器C代码
#include "stdio.h" /* 标准输入输出库*/#include "string.h" /* 字符串操作函数库*/#include "math.h" /* 数学函数库*/#include "stdlib.h" /* 标准函数库*/#include "graphics.h" /* 图形函数库*/#include "bios.h" /* 基本输入输出系统函数库*/#include "dos.h" /* dos函数库*/#define NUM0 0x5230 /* 小键盘区上数字键0 */ #define NUM1 0x4f31 /* 小键盘区上数字键1 */ #define NUM2 0x5032 /* 小键盘区上数字键2 */ #define NUM3 0x5133 /* 小键盘区上数字键3 */ #define NUM4 0x4b34 /* 小键盘区上数字键4 */ #define NUM5 0x4c35 /* 小键盘区上数字键5 */ #define NUM6 0x4d36 /* 小键盘区上数字键6 */ #define NUM7 0x4737 /* 小键盘区上数字键7 */ #define NUM8 0x4838 /* 小键盘区上数字键8 */ #define NUM9 0x4939 /* 小键盘区上数字键9 */ #define NUMPNT 0x532e /* 小键盘区上. 键*/ #define NUMADD 0x4e2b /* 小键盘区上+ 键*/ #define NUMSUB 0x4a2d /* 小键盘区上- 键*/ #define NUMMUL 0x372a /* 小键盘区上* 键*/ #define NUMDIV 0x352f /* 小键盘区上/ 键*/ #define NUMEQU 0x1c0d /* 小键盘区上= 键*/#define KEY0 0xb30 /* 主键盘区上数字键0 */ #define KEY1 0x231 /* 主键盘区上数字键1 */ #define KEY2 0x332 /* 主键盘区上数字键2 */ #define KEY3 0x433 /* 主键盘区上数字键3 */ #define KEY4 0x534 /* 主键盘区上数字键4 */ #define KEY5 0x635 /* 主键盘区上数字键5 */ #define KEY6 0x736 /* 主键盘区上数字键6 */ #define KEY7 0x837 /* 主键盘区上数字键7 */ #define KEY8 0x938 /* 主键盘区上数字键8 */ #define KEY9 0xa39 /* 主键盘区上数字键9 */ #define KEYPNT 0x342e /* 主键盘区上. 键*/ #define KEYSUB 0xc2d /* 主键盘区上- 键*/ #define KEYMUL 0x92a /* 主键盘区上* 键*/ #define KEYEQU 0xd3d /* 主键盘区上= 键*/#define SQR 0x340 /* @ 键,求平方根*/#define KEYR 0x1372 /* r 键,取倒数*/#define PERCENT 0x625 /* % 键,求百分数*/#define DEL 0x5300 /* DEL 键*/#define ESC 0x11b /* ESC 键*/#define BACKSPACE 0xe08 /* 退格键*/#define F9 0x4300 /* F9 键,正负数变换*/#define CTRL_L 0x260c /* Ctrl 键+L键,清除记忆器中的数值*/#define CTRL_R 0x1312 /* Ctrl 键+R键,读取记忆器中的数值*/#define CTRL_M 0x320d /* Ctrl 键+M键,将当前数值写入记忆器中*/#define CTRL_P 0x1910 /* Ctrl 键+P键,将当前数值和记忆器中保存的数值相加*/ #define ALT_X 0x2d00 /* Alt 键+X键*/#define TRUE 1 /* 为十进制1表示为真true */#define FALSE 0 /* 为十进制0表示为假false *//*计算器界面结构体*/struct Block{ int left,top,width,height; /* 左上坐标,宽,高*/char caption[50]; /* 标题*/int fontcolor,fontsize,status; /* 字体颜色,字体大小,状态*/ };void Form(struct Block form); /* 构造和显示主窗口*/void TextBox(struct Block txtbox); /* 构造和显示文本输入框*/void Label(struct Block label); /* 构造和显示标签,若记忆功能开启,标签标记为:M*/void CommandButton(struct Block cmdbutton); /*显示cmdbutton[i]命令按钮*/void CommandButton_KeyboardDown(int i); /*定义按下编号为i的键所进行的操作,如按钮的状态的改变*/void CommandButton_KeyboardUp(int i); /*定义松开编号为i的按键所进行的操作,如按钮的状态*/void InitApp(); /*初始化程序*/void Showme(); /*显示计算器界面*/void Load(); /*初始化默认值*/void CommandButton_Click(int key); /*按键盘时所做的操作*/void DoubleRun(); /*四则运算:加减乘除*/void SingleRun(int operatoror); /*单运算*/void Resetbuf(); /*重置缓冲区*/void StoreSet(int key); /*定义记忆存储操作*/void Unload(); /*退出系统时的一些恢复操作*/struct Block frmmain,txtscreen,lblstore,cmdbutton[28]; /*定义主窗口,文本输入框,记忆标签,28[0-27]个按钮*/int clickflag; /*clickflag:按键标志,*/int top,pointflag,digitkeyhit; /*top:保存缓冲区中的当前位数,pointflag:小数点标记,digitkeyhit:数字键按键标记*/int operatoror,runflag,ctnflag; /*operatoror:操作符,runflag:运算标记,ctnflag:运算符标记*/ int errorflag; /*错误标记*/double num1,num2,store; /*num1:操作数1,num2:操作数2,store:记忆变量*/char strbuf[33]; /*字符缓冲区,用于保存一个操作数*/void main(){int key; /*保存此计算器上定义的按键编号*/InitApp();/*初始化程序,进入图形模式*/Showme(); /*显示计算器窗口*/Load(); /*初始化默认值*/while(1){if(bioskey(1)==0) continue; /*直到有键按下时,才返回非0值,否则返回0值*/key=bioskey(0); /*返回上条语句的按键值*/switch(key) /*捕获相应的键盘按键并匹配到计算器按键上*/{ case NUM0:case KEY0: key=10;break;case NUM1:case KEY1: key=1;break;case NUM2:case KEY2: key=2;break;case NUM3:case KEY3: key=3;break;case NUM4:case KEY4: key=4;break;case NUM5:case KEY5: key=5;break;case NUM6:case KEY6: key=6;break;case NUM7:case KEY7: key=7;break;case NUM8:case KEY8: key=8;break;case NUM9:case KEY9: key=9;break;case F9: key=11;break;case NUMPNT:case KEYPNT: key=12;break;case NUMADD: key=13;break;case NUMSUB:case KEYSUB: key=14;break;case NUMMUL:case KEYMUL: key=15;break;case NUMDIV: key=16;break;case SQR: key=17;break;case PERCENT: key=18;break;case KEYR: key=19;break;case NUMEQU:case KEYEQU: key=20;break;case CTRL_L: key=21;break;case CTRL_R: key=22;break;case CTRL_M: key=23;break;case CTRL_P: key=24;break;case BACKSPACE: key=25;break;case DEL: key=26;break;case ESC: key=27;break;case ALT_X: key=0; break;default: key=-1;break;}if(key<0) continue; /*若对应的按键返回负数,则返回到while(1)处执行*/CommandButton_KeyboardDown(key);/*为了在计算器上显示按键效果,在此函数中改变一些按钮的状态值*/CommandButton_Click(key); /*根据key的值,进行相关操作*/delay(300000); /*为了突出按键效果,此处延时300000毫秒*/CommandButton_KeyboardUp(key); /*在处理完此按键后,要恢复按钮的状态值*/}}void InitApp() /*初始化程序*/{int driver=DETECT,mode; /* 显示设备驱动为自动检测显示器模式*/initgraph(&driver,&mode,""); /* 初始化图形显示系统*/if(driver!=VGA&&driver!=EGA) /* 如果不能初始化*/{ printf("\n\nERROR!Can't initialize the graphics system!"); /* 显示错误信息"不能初始化图形系统" */closegraph(); /* 关闭图形接口*/exit(0); /* 直接退出系统*/}setbkcolor(9); /* 设置背景颜色为青色*//*主窗口的属性设置*/frmmain.left=200; frmmain.top=100; frmmain.width=230; frmmain.height=235; frmmain.fontcolor=BLACK; frmmain.fontsize=1; strcpy(frmmain.caption," << Calculator >>");frmmain.status=1;/*文本框的属性设置*/txtscreen.left=10;txtscreen.top=25;txtscreen.width=210;txtscreen.height=30;txtscreen.fontcolor=B LACK;txtscreen.fontsize=1;strcpy(txtscreen.caption,"0."); txtscreen.status=1;/*标签的属性设置*/lblstore.left=190; lblstore.top=62; lblstore.width=30; lblstore.height=25; lblstore.fontcolor=YELLOW; lblstore.fontsize=1;strcpy(lblstore.caption,""); lblstore.status=1;/*命令按钮的属性设置*/cmdbutton[1].left=50-35;cmdbutton[1].top=165;cmdbutton[1].width=30;cmdbutton[1].height=25; cmdbutton[1].fontcolor=BLUE;cmdbutton[1].fontsize=1;strcpy(cmdbutton[1].caption,"1");cmdbu tton[1].status=1;cmdbutton[2].left=85-35;cmdbutton[2].top=165;cmdbutton[2].width=30;cmdbutton[2].height=25; cmdbutton[2].fontcolor=BLUE;cmdbutton[2].fontsize=1;strcpy(cmdbutton[2].caption,"2");cmdbu tton[2].status=1;cmdbutton[3].left=120-35;cmdbutton[3].top=165;cmdbutton[3].width=30;cmdbutton[3].height=2 5;cmdbutton[3].fontcolor=BLUE;cmdbutton[3].fontsize=1;strcpy(cmdbutton[3].caption,"3");cmd button[3].status=1;cmdbutton[4].left=50-35;cmdbutton[4].top=130;cmdbutton[4].width=30;cmdbutton[4].height=25; cmdbutton[4].fontcolor=BLUE;cmdbutton[4].fontsize=1;strcpy(cmdbutton[4].caption,"4");cmdbu tton[4].status=1;cmdbutton[5].left=85-35;cmdbutton[5].top=130;cmdbutton[5].width=30;cmdbutton[5].height=25; cmdbutton[5].fontcolor=BLUE;cmdbutton[5].fontsize=1;strcpy(cmdbutton[5].caption,"5");cmdbu tton[5].status=1;cmdbutton[6].left=120-35;cmdbutton[6].top=130;cmdbutton[6].width=30;cmdbutton[6].height=2 5;cmdbutton[6].fontcolor=BLUE;cmdbutton[6].fontsize=1;strcpy(cmdbutton[6].caption,"6");cmd button[6].status=1;cmdbutton[7].left=50-35;cmdbutton[7].top=95;cmdbutton[7].width=30;cmdbutton[7].height=25;c mdbutton[7].fontcolor=BLUE;cmdbutton[7].fontsize=1;strcpy(cmdbutton[7].caption,"7");cmdbutt on[7].status=1;cmdbutton[8].left=85-35;cmdbutton[8].top=95;cmdbutton[8].width=30;cmdbutton[8].height=25;c mdbutton[8].fontcolor=BLUE;cmdbutton[8].fontsize=1;strcpy(cmdbutton[8].caption,"8");cmdbutt on[8].status=1;cmdbutton[9].left=120-35;cmdbutton[9].top=95;cmdbutton[9].width=30;cmdbutton[9].height=25; cmdbutton[9].fontcolor=BLUE;cmdbutton[9].fontsize=1;strcpy(cmdbutton[9].caption,"9");cmdbu tton[9].status=1;cmdbutton[10].left=50-35;cmdbutton[10].top=200;cmdbutton[10].width=30;cmdbutton[10].height =25;cmdbutton[10].fontcolor=BLUE;cmdbutton[10].fontsize=1;strcpy(cmdbutton[10].caption,"0" );cmdbutton[10].status=1;cmdbutton[11].left=85-35;cmdbutton[11].top=200;cmdbutton[11].width=30;cmdbutton[11].height =25;cmdbutton[11].fontcolor=BLUE;cmdbutton[11].fontsize=1;strcpy(cmdbutton[11].caption,"+/-");cmdbutton[11].status=1;cmdbutton[12].left=120-35;cmdbutton[12].top=200;cmdbutton[12].width=30;cmdbutton[12].heig ht=25;cmdbutton[12].fontcolor=BLUE;cmdbutton[12].fontsize=1;strcpy(cmdbutton[12].caption,". ");cmdbutton[12].status=1;cmdbutton[13].left=155-35;cmdbutton[13].top=95;cmdbutton[13].width=30;cmdbutton[13].height =25;cmdbutton[13].fontcolor=RED;cmdbutton[13].fontsize=1;strcpy(cmdbutton[13].caption,"+"); cmdbutton[13].status=1;cmdbutton[14].left=155-35;cmdbutton[14].top=130;cmdbutton[14].width=30;cmdbutton[14].heig ht=25;cmdbutton[14].fontcolor=RED;cmdbutton[14].fontsize=1;strcpy(cmdbutton[14].caption,"-" );cmdbutton[14].status=1;cmdbutton[15].left=155-35;cmdbutton[15].top=165;cmdbutton[15].width=30;cmdbutton[15].heig ht=25;cmdbutton[15].fontcolor=RED;cmdbutton[15].fontsize=1;strcpy(cmdbutton[15].caption,"*" );cmdbutton[15].status=1;cmdbutton[16].left=155-35;cmdbutton[16].top=200;cmdbutton[16].width=30;cmdbutton[16].heig ht=25;cmdbutton[16].fontcolor=RED;cmdbutton[16].fontsize=1;strcpy(cmdbutton[16].caption,"/" );cmdbutton[16].status=1;cmdbutton[17].left=190-35;cmdbutton[17].top=95;cmdbutton[17].width=30;cmdbutton[17].height =25;cmdbutton[17].fontcolor=BLUE;cmdbutton[17].fontsize=1;strcpy(cmdbutton[17].caption,"sq r");cmdbutton[17].status=1;cmdbutton[18].left=190-35;cmdbutton[18].top=130;cmdbutton[18].width=30;cmdbutton[18].heig ht=25;cmdbutton[18].fontcolor=BLUE;cmdbutton[18].fontsize=1;strcpy(cmdbutton[18].caption," %");cmdbutton[18].status=1;cmdbutton[19].left=190-35;cmdbutton[19].top=165;cmdbutton[19].width=30;cmdbutton[19].heig ht=25;cmdbutton[19].fontcolor=BLUE;cmdbutton[19].fontsize=1;strcpy(cmdbutton[19].caption," 1/x");cmdbutton[19].status=1;cmdbutton[20].left=190-35;cmdbutton[20].top=200;cmdbutton[20].width=30;cmdbutton[20].heig ht=25;cmdbutton[20].fontcolor=RED;cmdbutton[20].fontsize=1;strcpy(cmdbutton[20].caption,"= ");cmdbutton[20].status=1;cmdbutton[21].left=190;cmdbutton[21].top=95;cmdbutton[21].width=30;cmdbutton[21].height=2 5;cmdbutton[21].fontcolor=RED;cmdbutton[21].fontsize=1;strcpy(cmdbutton[21].caption,"MC"); cmdbutton[21].status=1;cmdbutton[22].left=190;cmdbutton[22].top=130;cmdbutton[22].width=30;cmdbutton[22].height= 25;cmdbutton[22].fontcolor=RED;cmdbutton[22].fontsize=1;strcpy(cmdbutton[22].caption,"MR") ;cmdbutton[22].status=1;cmdbutton[23].left=190;cmdbutton[23].top=165;cmdbutton[23].width=30;cmdbutton[23].height= 25;cmdbutton[23].fontcolor=RED;cmdbutton[23].fontsize=1;strcpy(cmdbutton[23].caption,"MS") ;cmdbutton[23].status=1;cmdbutton[24].left=190;cmdbutton[24].top=200;cmdbutton[24].width=30;cmdbutton[24].height= 25;cmdbutton[24].fontcolor=RED;cmdbutton[24].fontsize=1;strcpy(cmdbutton[24].caption,"M+") ;cmdbutton[24].status=1;cmdbutton[25].left=50-35;cmdbutton[25].top=60;cmdbutton[25].width=53;cmdbutton[25].height =25;cmdbutton[25].fontcolor=RED;cmdbutton[25].fontsize=1;strcpy(cmdbutton[25].caption,"<-") ;cmdbutton[25].status=1;cmdbutton[26].left=108-35;cmdbutton[26].top=60;cmdbutton[26].width=53;cmdbutton[26].height =25;cmdbutton[26].fontcolor=RED;cmdbutton[26].fontsize=1;strcpy(cmdbutton[26].caption,"Del ");cmdbutton[26].status=1;cmdbutton[27].left=166-35;cmdbutton[27].top=60;cmdbutton[27].width=53;cmdbutton[27].height =25;cmdbutton[27].fontcolor=RED;cmdbutton[27].fontsize=1;strcpy(cmdbutton[27].caption,"Esc ");cmdbutton[27].status=1;/* 设置计算器界面*/}void Showme() /*显示计算器界面*/{ int i;Form(frmmain); /*显示主窗口,frmmain为主窗口的结构变量名*/TextBox(txtscreen); /*显示文本框*/Label(lblstore); /*显示记忆器的状态标签*/for(i=1;i<28;i++) /*显示27个按钮在计算器主窗口中*/CommandButton(cmdbutton[i]);}void Load() /*初始化默认值*/{ num1=num2=0;Resetbuf();ctnflag=FALSE;operatoror=0;runflag=FALSE;errorflag=FALSE;store=0;clickflag=FALSE;strcpy(txtscreen.caption,"0.");TextBox(txtscreen);/*文本框中初始显示为0.的字符*/strcpy(lblstore.caption,"");Label(lblstore);}void Unload() /*退出系统*/{cleardevice(); /*清除图形屏幕*/closegraph(); /*关闭图形系统*/exit(0);}void Resetbuf(){ strbuf[0]=' ';strbuf[1]=0;top=1;digitkeyhit=FALSE;pointflag=FALSE;}void Form(struct Block form) /* 构造和显示主窗口*/{ int x1=form.left; /*窗口左上角的横坐标值*/int y1=form.top; /*窗口左上角的纵坐标值*/int x2=form.width+x1-1;/*窗口右下角的横坐标值*/int y2=form.height+y1-1; /*窗口右下角的纵坐标值*/setfillstyle(SOLID_FILL,LIGHTGRAY); /*设置填充模式和颜色*/bar(x1+1,y1+1,x2-1,y2-1); /*画一个淡灰色的填充窗口,作为主窗口,但此函数不画出边框*/setcolor(WHITE); /*设置当前画线颜色*/line(x1,y1,x2,y1);line(x1,y1,x1,y2); /*用白线画边框左边和上边的线,美化主窗口*/ setcolor(DARKGRAY); /*设置填充模式和颜色*/line(x2,y1,x2,y2);line(x1,y2,x2,y2); /*用深灰色画边框右边和下边的线,美化主窗口*/ setfillstyle(SOLID_FILL,RED);bar(x1+2,y1+2,x2-2,y1+15); /*设置标题栏颜色为红色*/settextjustify(LEFT_TEXT,CENTER_TEXT); /*设置文本的对齐方式为左中对齐*/settextstyle(DEFAULT_FONT,0,form.fontsize); /*设置文本显示字体为默认字体,大小为主窗体字体大小*/setcolor(form.fontcolor);outtextxy(x1+3,y1+10,form.caption); /*用主窗体的颜色显示标题在标题栏*/if(form.status&1) /*判断窗口是否可用,未使用ALT+X键,右上角的X按钮*/ { cmdbutton[0].left=form.width-15;cmdbutton[0].top=3;cmdbutton[0].width=12;cmdbutton[0].height=12;cmdbutton[0].status=1;cmdbutton[0].caption[0]=0;CommandButton(cmdbutton[0]);x1=cmdbutton[0].left+form.left;y1=cmdbutton[0].top+form.top;x2=cmdbutton[0].width+x1-1;y2=cmdbutton[0].height+y1-1;setfillstyle(SOLID_FILL,LIGHTGRAY);bar(x1+1,y1+1,x2-1,y2-1);setcolor(DARKGRAY);line(x1+2,y1+2,x2-2,y2-2);line(x2-2,y1+2,x1+2,y2-2);}}void TextBox(struct Block txtbox) /* 设置和显示输入框*/{ /*(x1,y1),(x2,y2)为主窗口中的相对坐标*/int x1=txtbox.left+frmmain.left;int y1=txtbox.top+frmmain.top;int x2=txtbox.width+x1-1;int y2=txtbox.height+y1-1;setfillstyle(SOLID_FILL,WHITE);bar(x1+1,y1+1,x2-1,y2-1);/*因bar()不画出边框,所以接下来画这个方本框的边框线*/setcolor(LIGHTGRAY);rectangle(x1+1,y1+1,x2-1,y2-1);setcolor(DARKGRAY);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(WHITE);line(x2,y1,x2,y2);line(x1,y2,x2,y2);settextjustify(RIGHT_TEXT,CENTER_TEXT); /*为图形函数设置文本的对齐方式,第一参数为水平对齐方式,第二参数为垂直对齐方式*/settextstyle(DEFAULT_FONT,0,txtbox.fontsize); /*为图形输出设置当前的文本属性:字体,方向,大小*/setcolor(txtbox.fontcolor); /*设置方本框的字体颜色*/outtextxy(x2-10,(y1+y2)/2,txtbox.caption); /*在指定位置显示txtbox.caption的字符串值*/}void Label(struct Block label) /*设置和显示计算器记忆功能的使用状态,默认为空*/ { int x1=label.left+frmmain.left;int y1=label.top+frmmain.top;int x2=label.width+x1-1;int y2=label.height+y1-1;setfillstyle(SOLID_FILL,LIGHTGRAY);bar(x1+1,y1+1,x2-1,y2-1);setcolor(DARKGRAY);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(WHITE);line(x2,y1,x2,y2);line(x1,y2,x2,y2);settextjustify(CENTER_TEXT,CENTER_TEXT);settextstyle(DEFAULT_FONT,0,label.fontsize);setcolor(label.fontcolor);outtextxy((x1+x2)/2,(y1+y2)/2,label.caption);}void CommandButton(struct Block cmdbutton) /*设置和显示单个按钮*/{ /*(x1,y1),(x2,y2)为主窗口中的相对坐标*/int x1=cmdbutton.left+frmmain.left;int y1=cmdbutton.top+frmmain.top;int x2=cmdbutton.width+x1-1;int y2=cmdbutton.height+y1-1;int c1,c2;/*按钮的初始状态为1,若有键按下后,其状态变为0,处理完按键操作后,又恢复为状态1*/if(cmdbutton.status) /*根据按钮的当前状态值来,分别用不同的颜色边框来重绘此按钮*/{ c1=WHITE; /*白色*/c2=DARKGRAY; /*深灰色*/}else /*若刚有键按下*/{ c1=DARKGRAY;c2=WHITE;}setcolor(c1);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(c2);line(x2,y1,x2,y2);line(x1,y2,x2,y2);settextjustify(CENTER_TEXT,CENTER_TEXT);settextstyle(DEFAULT_FONT,0,cmdbutton.fontsize);outtextxy((x1+x2)/2,(y1+y2)/2,cmdbutton.caption);}void CommandButton_KeyboardDown(int i) /*按下某键时所做的操作*/{ clickflag=TRUE; /*键盘点击标志*/cmdbutton[i].status=0;CommandButton(cmdbutton[i]); /*用与初始时不同的边框颜色色,重绘此命令按钮*/}void CommandButton_KeyboardUp(int key) /*当按键处理完后,恢复按钮状态,重绘此命令按钮*/{ clickflag=FALSE;cmdbutton[key].status=1;CommandButton(cmdbutton[key]);}void CommandButton_Click(int key) /*处理相应按键操作*/{if(errorflag==TRUE) return;switch(key){ case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9: /*1-9*/if(top<15) /*单个操作数小于15位*/{ strbuf[top++]='0'+key; /*'0'+key表示是字符1,若没有'0'+则存储的是Ascll码为key为字符*/strbuf[top]=0; /*存储的是ASCLL码为0的表示的字符Ctrl+@*/digitkeyhit=TRUE; /*表示已有数字键按下*/strcpy(txtscreen.caption,strbuf); /*在文本框中显示当前的*/}runflag=FALSE; /*运算标记为假*/if(ctnflag==FALSE) operatoror=0;break;case 10: /* 0输入*/if(top<15&&top!=1){ strbuf[top++]='0';strbuf[top]=0;strcpy(txtscreen.caption,strbuf);}digitkeyhit=TRUE;runflag=FALSE;if(ctnflag==FALSE) operatoror=0;break;case 11: /*正负互换*/if(digitkeyhit==TRUE){ strbuf[0]=strbuf[0]==' '?'-':' ';strcpy(txtscreen.caption,strbuf);}else if(runflag==TRUE) /*表示没有新的输入,就是在之前的计算结果上正负转换*/{ num1=-num2;sprintf(txtscreen.caption,"%G",num1);}else /*原数的正负互换*/{ num1=-num1;sprintf(txtscreen.caption,"%G",num1);}runflag=FALSE;if(ctnflag==FALSE) operatoror=0;break;case 12: /*输入一个小数点*/if(top==1) /*表示还没有输入数,保持0.状态*/{ strbuf[top++]='0';strbuf[top++]='.';strbuf[top]=0;strcpy(txtscreen.caption,strbuf);digitkeyhit=TRUE;runflag=FALSE;pointflag=TRUE;if(ctnflag==FALSE) operatoror=0;}else if(top<15&&pointflag==FALSE){ strbuf[top++]='.';strbuf[top]=0;strcpy(txtscreen.caption,strbuf);digitkeyhit=TRUE;runflag=FALSE;pointflag=TRUE;if(ctnflag==FALSE) operatoror=0;}break;case 13:case 14:case 15:case 16: /* 四则运算加减乘除运算符*/ if(digitkeyhit) /*若此运算符之前已经输入了一个数*/num1=atof(strbuf);if(ctnflag) /*之前的输入中,已有运算符的输入*/if(digitkeyhit==TRUE) /*如1+2+的情况*/DoubleRun(); /*先计算出1+2*/else;else /*之前的输入中,没有运算符的输入,如:1+的情况*/ if(operatoror==0)num2=num1;else;Resetbuf();operatoror=key;ctnflag=TRUE;runflag=TRUE;break;case 17:case 18:case 19: /*单运算开方,百分比,倒数*/ if(digitkeyhit)num1=atof(strbuf); /*num1保存当前操作数*/SingleRun(key);Resetbuf();ctnflag=FALSE;operatoror=0;runflag=FALSE;break;case 20: /*获取运算结果及等于操作*/if(digitkeyhit) num1=atof(strbuf);if(operatoror)DoubleRun(); /*第一个操作数,保存在num2中*/ elsenum2=num1;Resetbuf();ctnflag=FALSE;runflag=TRUE;break;case 21:case 22:case 23:case 24: /*值的保存的一些操作*/ if(digitkeyhit) num1=atof(strbuf);StoreSet(key);Resetbuf();break;case 25: /*删除数字的整数部分的最后一位数(BackSpace键)*/ if(top>1)if(strbuf[--top]=='.'){ if(strbuf[1]=='0'&&strbuf[2]=='.')strbuf[--top]=0;elsestrbuf[top]=0;pointflag=FALSE;}elsestrbuf[top]=0;operatoror=0;ctnflag=FALSE;runflag=FALSE;strcpy(txtscreen.caption,strbuf);break;case 26: /*清除当前显示的值(Del键)*/Resetbuf();num1=0;strcpy(txtscreen.caption,strbuf);TextBox(txtscreen);break;case 27: /*清除所有的值,包括存储的,已经运算了的(ESC键)*/ Resetbuf();num1=num2=0;ctnflag=FALSE;operatoror=0;runflag=FALSE;errorflag=FALSE;strcpy(txtscreen.caption,"0.");TextBox(txtscreen);break;case 0:Unload();}if(errorflag==FALSE){ if(atof(txtscreen.caption)==0)strcpy(txtscreen.caption,"0");if(strchr(txtscreen.caption,'.')==NULL)strcat(txtscreen.caption,".");}TextBox(txtscreen); /*显示txtscreen结构变量的值*/ }void DoubleRun() /*四则运算*/{ switch(operatoror){ case 13: num2+=num1;break; /*加*/case 14: num2-=num1;break; /*减*/case 15: num2*=num1;break; /*乘*/case 16: if(num1==0) /*除*/errorflag=TRUE;elsenum2/=num1;break;}if(errorflag)strcpy(txtscreen.caption,"Can't divide by zero!");elsesprintf(txtscreen.caption,"%G",num2);}void SingleRun(int key) /*单运算*/{ switch(key){ case 17: /*求开方*/if(num1<0)errorflag=TRUE;elsenum1=sqrt(num1);break;case 18: /*求百分比*/num1/=100;break;case 19: /*求倒数*/if(num1==0)errorflag=TRUE;elsenum1=1/num1;}if(errorflag==TRUE)if(num1<0)strcpy(txtscreen.caption,"Can't blower than zero!");elsestrcpy(txtscreen.caption,"Can't equal to zero!");elsesprintf(txtscreen.caption,"%G",num1);}void StoreSet(int key) /*记忆存储操作*/{ switch(key){ case 21: /*保存清除*/store=0;lblstore.caption[0]=0;break;case 22: /*取出保存的值*/num1=store;sprintf(txtscreen.caption,"%G",store);runflag=FALSE;if(ctnflag==FALSE) operatoror=0;break;case 23: /*保存当前数字*/store=num1;strcpy(lblstore.caption,"M");break;case 24: /*保存值与当前数字相加*/store+=num1;strcpy(lblstore.caption,"M");break;}Label(lblstore);}。
简单计算器c语言源码
#include <stdio.h>#include <string.h>#include <ctype.h>#include <math.h>//expression evaluate#define iMUL 0#define iDIV 1#define iADD 2#define iSUB 3#define iCap 4//#define LtKH 5//#define RtKH 6#define MaxSize 100void iPush(float);float iPop();float StaOperand[MaxSize];int iTop=-1;//char Srcexp[MaxSize];char Capaexp[MaxSize];char RevPolishexp[MaxSize];float NumCapaTab[26];char validexp[]="*/+-()";char NumSets[]="0123456789";char StackSymb[MaxSize];int operands;//void NumsToCapas(char [], int , char [], float []);int CheckExpress(char);int PriorChar(char,char);int GetOperator(char [], char);void counterPolishexp(char INexp[], int slen, char Outexp[]); float CalcRevPolishexp(char [], float [], char [], int);void main(){char ch;char s;int bl=1;while(bl==1){int ilen;float iResult=0.0;printf("输入计算表达式(最后以=号结束):\n");memset(StackSymb,0,MaxSize);memset(NumCapaTab,0,26); //A--NO.1, B--NO.2, etc.gets(Srcexp);ilen=strlen(Srcexp);NumsToCapas(Srcexp,ilen,Capaexp,NumCapaTab);ilen=strlen(Capaexp);counterPolishexp(Capaexp,ilen,RevPolishexp);ilen=strlen(RevPolishexp);iResult=CalcRevPolishexp(validexp, NumCapaTab, RevPolishexp,ilen);printf("\n计算结果:\n%.6f\n",iResult);printf("是否继续运算?(Y/N)\n");ch=getchar();s=getchar();//接受回车if(ch=='y'||ch=='Y'){bl=1;}else{bl=0;}}}void iPush(float value){if(iTop<MaxSize) StaOperand[++iTop]=value;}float iPop(){if(iTop>-1)return StaOperand[iTop--];return -1.0;}void NumsToCapas(char Srcexp[], int slen, char Capaexp[], float NumCapaTab[]) {char ch;int i, j, k, flg=0;int sign;float val=0.0,power=10.0;i=0; j=0; k=0;while (i<slen){ch=Srcexp[i];if (i==0){sign=(ch=='-')?-1:1;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';}if (ch=='.'){while(isdigit(ch=Srcexp[++i])) {val=val+(ch-'0')/power; power*=10;}} //end ifif(flg){val*=sign;flg=0;}} //end if//write Capaexp array// write NO.j to arrayif(val){Capaexp[k++]='A'+j; Capaexp[k++]=ch;NumCapaTab[j++]=val; //A--0, B--1,and C, etc.}else{Capaexp[k++]=ch;}val=0.0;power=10.0;//i++;}Capaexp[k]='\0';operands=j;}float CalcRevPolishexp(char validexp[], float NumCapaTab[], char RevPolishexp[], int slen) {float sval=0.0, op1,op2;int i, rt;char ch;//recursive stacki=0;while((ch=RevPolishexp[i]) && i<slen){switch(rt=GetOperator(validexp, ch)){case iMUL: op2=iPop(); op1=iPop();sval=op1*op2;iPush(sval);break;case iDIV: op2=iPop(); op1=iPop();if(!fabs(op2)){printf("overflow\n");iPush(0);break;}sval=op1/op2;iPush(sval);break;case iADD: op2=iPop(); op1=iPop();sval=op1+op2;iPush(sval);break;case iSUB: op2=iPop(); op1=iPop();sval=op1-op2;iPush(sval);break;case iCap: iPush(NumCapaTab[ch-'A']); break;default: ;}++i;}while(iTop>-1){sval=iPop();}return sval;}int GetOperator(char validexp[],char oper) {int oplen,i=0;oplen=strlen(validexp);if (!oplen) return -1;if(isalpha(oper)) return 4;while(i<oplen && validexp[i]!=oper) ++i;if(i==oplen || i>=4) return -1;return i;}int CheckExpress(char ch){int i=0;char cc;while((cc=validexp[i]) && ch!=cc) ++i;if (!cc)return 0;return 1;}int PriorChar(char curch, char stach){//栈外优先级高于(>)栈顶优先级时,才入栈//否则(<=),一律出栈if (curch==stach) return 0; //等于时应该出栈else if (curch=='*' || curch=='/'){if(stach!='*' && stach!='/')return 1;}else if (curch=='+' || curch=='-'){if (stach=='(' || stach==')')return 1;}else if (curch=='('){if (stach==')')return 1;}return 0;}void counterPolishexp(char INexp[], int slen, char Outexp[]) {int i, j, k,pr;char t;i=0;j=k=0;while (INexp[i]!='=' && i<slen){if (INexp[i]=='(')StackSymb[k++]=INexp[i];//iPush(*(INexp+i));else if(INexp[i]==')'){//if((t=iPop())!=-1)while((t=StackSymb[k-1])!='('){Outexp[j++]=t;k--;}k--;}else if (CheckExpress(INexp[i])) // is oparator{// printf("operator %c k=%d\n",INexp[i],k);while (k){// iPush(*(INexp+i));if(pr=PriorChar(INexp[i],StackSymb[k-1])) break;else{//if ((t=iPop())!=-1)t=StackSymb[k-1]; k--;Outexp[j++]=t;}} //end whileStackSymb[k++]=INexp[i]; //common process }else //if() 变量名{// printf("operand %c k=%d\n",INexp[i],k); Outexp[j++]=INexp[i];}i++; //}while (k){t=StackSymb[k-1]; k--;Outexp[j++]=t;}Outexp[j]='\0';}。
计算器(c 语言)实现源代码
计算器(c++语言)实现源代码.txt如果真诚是一种伤害,请选择谎言;如果谎言是一种伤害,请选择沉默;如果沉默是一种伤害,请选择离开。
#include <iostream>using namespace std;#define STACK_INIT_SIZE 100#define STACKINCREMENT 10//-----------------------------------------------------------------------------------------------class Stack1{//定义字符栈public:char * base;char * top;int stacksize;Stack1();int GetTop(char &e);//取栈顶元素int Push(char e);//压栈int Pop(char &e);//跳栈};Stack1::Stack1(){base=(char *)malloc(STACK_INIT_SIZE*sizeof(char));top=base;stacksize=STACK_INIT_SIZE;}int Stack1::GetTop(char &e){if (top==base) return -1;else {e=*(top-1);return 0;}}int Stack1::Push(char e){char *new_base=0;if(top-base>=stacksize){new_base=(char *)realloc(base,(stacksize+STACKINCREMENT)*sizeof(char));if(!new_base) return -2;else{base=new_base;top=base+stacksize;stacksize+=STACKINCREMENT;}}*top++=e;return 0;}int Stack1::Pop(char &e){if(top==base) return -1;e=*--top;return 0;}//----------------------------------------------------------------------------------------------class Stack2{//定义数字栈public:double * base;double * top;int stacksize;Stack2();int GetTop(double &e);//取栈顶元素int Push(double e);//压栈int Pop(double &e);//跳栈};Stack2::Stack2(){base=(double *)malloc(STACK_INIT_SIZE*sizeof(double));top=base;stacksize=STACK_INIT_SIZE;}int Stack2::GetTop(double &e){if (top==base) return -1;e=*(top-1);return 0;}int Stack2::Push(double e){double *new_base=0;if(top-base>=stacksize){new_base=(double*)realloc(base,(stacksize+STACKINCREMENT)*sizeof(double));if(!new_base) return -2;else{new_base=base;top=base+stacksize;stacksize+=STACKINCREMENT;}}*top++=e;return 0;}int Stack2::Pop(double &e){if(top==base) return -1;e=*--top;return 0;}//------------------------------------------------------------------------------------------------class Calculator{private:bool IsOperand(char ch);//判断ch是否是操作数bool IsOperator(char ch);//判断ch是否是操作符char Precede(char op1,char op2);//判断两个操作符优先级的高低double Operate(double left,char op,double right);//执行运算left op right int Translate(char op);//将操作符映射到行、列游标public:void Run();//执行表达式求值运算};bool Calculator::IsOperand(char ch){if(ch>47&&ch<58) return true;else return false;}bool Calculator::IsOperator(char ch){if(ch>39&&ch<44||ch==45||ch==47||ch==61) return true;else return false;}char Calculator::Precede(char op1,char op2){int op10,op20;op10=op20=0;op10=Translate(op1);op20=Translate(op2);charOP[7][7]={'>','>','<','<','<','>','>','>','>','<','<','<','>','>','>','>','>','> ','<','>','>','>','>','>','>','<','>','>','<','<','<','<','<','=','e','>','>','> ','>','e','>','>','<','<','<','<','<','e','='};return OP[op10][op20];//将操作符优先级表映射到二维数组}double Calculator::Operate(double left,char op,double right){ switch(op){case '+':return (left+right);break;case '-':return (left-right);break;case '*':return (left*right);break;case '/':return (left/right);break;}}int Calculator::Translate(char op){switch(op){case '+':return 0;break;case '-':return 1;break;case '*':return 2;break;case '/':return 3;break;case '(':return 4;break;case ')':return 5;break;case '=':return 6;break;}}void Calculator::Run(){Stack1 OPTR;Stack2 OPND;char c;//用于临时存放输入的操作数或操作符char c0;//用于存放操作符栈顶的操作符char x;//用于存放弹出相同操作符后返回的操作符double a=0,b=0;double r=0;//用于存放运算结果int flag=0;//标记异常OPTR.Push('=');OPTR.GetTop(c0);cout<<"输入格式例如“3+4/(3-1)=”"<<endl;c=getchar();while(c!='='||c0!='='){if(IsOperand(c)) {OPND.Push(c-48);c=getchar();}else if(IsOperator(c)){switch(Precede(c0,c)){case '<':OPTR.Push(c);OPTR.GetTop(c0);c=getchar();break;case '=':OPTR.Pop(x);OPTR.GetTop(c0);c=getchar();break;case '>':OPTR.Pop(c0);OPND.Pop(b);OPND.Pop(a);OPND.Push(Operate(a,c0,b));OPTR.GetTop(c0);break;default:cout<<"输入有误!"<<endl;flag=-1;break;}}else {cout<<"未输入等于号“=”!"<<endl;flag=-1;break;}if (flag==-1) {break;}}if (flag!=-1){OPND.GetTop(r);cout<<"结果为:"<<r<<endl;}}void main (){Calculator C;C.Run();}。
计算器编程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++语言编程计算器源代码
//计算器,函数#include <iostream>#include <string>#include <ctime>#include <conio.h>#include <cstdlib>#include <cmath>#include <vector>#include <cctype>using namespace std;double simple (string s);//简单运算bool check (char c);//检查是否为数值doublecou (double m,doublen,int c);//用于计算两个数的运算string cut (string str);//括号截取double senior (string str,double x);//高级函数计算double count (string st);//括号运算boolbr_l (char c);boolbr_r (char c);string al (string st);//特殊值与符号处理string abs_cut (string st);//绝对值处理intnum;string s;vector <double> b;//存储高级符号内值int main (){ cout<<"\n\t\t本软件由松哥独家制造\n\n"; while (true){ int i=0,j=0;num=0;string s1;b.clear ();cout<<"输入:"; cin>>s1;string s2(s1);if (s=="#") break;cout<<"输出:"<<s2<<"="<<count (s1)<<endl;} cout<<"\n\t\t感谢您的支持!!!!";}double simple (string st){ int i=0,j=0,k=0;vector <double> p;//存储读入的数字vector <int> q;//存储读入运算符while (st[i]!='\0'&&st[i]!='='){double sum=0;while (!check (st[i])) i++;while (check (st[i])){if (st[i]>64&&st[i]<91){sum=b[st[i]-65];i++;break;}if (st[i]!='.') sum=sum*10+(st[i++]-48);else {i++;double su=0,m=1;while (check (st[i])){m*=10.0;su=su*10+(st[i++]-48);}sum=sum+su/m;}}p.push_back (sum); }if (st[0]=='-') p[0]=-p[0];for (i=1;st[i]!='\0';i++){switch (st[i]){case '=':break;case '^': q.push_back (1);break;case '/': q.push_back (-3);break;case '*': q.push_back (3);break;case '+': q.push_back (4);break;case '-' :q.push_back (-4) ;break;default :if (!check (st[i])) {cout<<"含未知符号"<<st[i]<<"!\n"; return 0;}}}i=p.size (),j=q.size ();if (j==1) return cou (p[0],p[1],q[0]);else while (i!=1)for (int k=0;k<j;k++) {if (k==j-1&&abs (q[k])<abs (q[k-1])){p[k]=cou (p[k],p[k+1],q[k]); i--;j--; for (k;k<q.size ()-1;k++) {p[k+1]=p[k+2];q[k]=q[k+1];}p.pop_back ();q.pop_back ();break;}else if (abs (q[k])<=abs (q[k+1])) {p[k]=cou (p[k],p[k+1],q[k]); i--;j--;for (k;k<q.size ()-1;k++) {p[k+1]=p[k+2];q[k]=q[k+1];}p.pop_back ();q.pop_back ();if (j==1) break; } }return p[0];}bool check (char c){if (c>='0'&&c<='9'||c=='.'||c>64&&c<85) return true;else return false;}doublecou (double m,doublen,int c) {switch (c){case 1:return pow (m,n);case 3:return (m*n);case -3:return (m/n);case 4:return (m+n);case -4:return (m-n);default :cout<<c<<"无法计算!\n";} }string cut (string str){int i=0,m=0,n=0,r=0;string se;for (int j=0;j<str.size ();j++){if (br_l (str[j])) {m=j;i++;}if (br_r (str[j])) {n=j;if (n!=0) break;}}if (i==0) return str;if (m>0&&isalpha (str[m-1]))for (int k=m-1;;k--)if (k<0||!isalpha (str[k])) {k++;se=str.substr (k,m-k);int l=n-m+1;s=str.substr (m+1,l-2);b.push_back (senior (se,simple (s)));num++;l=n-k+1;str.replace (k,l,1,(char) (64+num)); returnstr;}int l=n-m+1;s=str.substr (m+1,l-2);b.push_back (simple (s));num++;str.replace (m,l,1,(char) (64+num)); returnstr;}double count (string st){ st=al (st);st=abs_cut (st);while (true){int r=0;st=cut (st);for (int i=0;i<st.size ();i++)if (br_r (st[i])) r++;if (r==0) break;}return simple (st);}boolbr_l (char c) {if (c=='('||c=='['||c=='{') return true;else return false;}boolbr_r (char c) {if (c==')'||c==']'||c=='}')return true;else return false;}string al (string st){inti,j=0;double m=0,n=1;for (i=0;i<st.size ();i++){if (st[i]=='e') {num++;st.replace (i,1,1,(char)(64+num));b.push_back (pow (2,1/log (2)));}if (st[i]=='p') {num++;st.replace (i,2,1,(char)(64+num));b.push_back (3.141593);}if (st[i]=='!'){j=i-1;while (j>0) {j--;if (st[j]=='.'){cout<<"只能计算整数的阶乘!!!\n";return "0";}if (st[j]<48||st[j]>57) {j++;break;}}for (int k=j;k<i;k++)m=m*10+(st[k]-48);for (m;m>1;m--) n*=m; num++;st.replace (j,i-j+1,1,(char)(64+num));b.push_back (n);}}i=st.find ("π");if (i<st.size ()) {num++;st.replace (i,2,1,(char)(64+num));b.push_back (acos (-1.0));}i=st.find ("∞");if (i<st.size ()) {num++;st.replace (i,3,1,(char)(64+num));b.push_back (DBL_MAX);}returnst;}stringabs_cut (string st){ inti;vector<int> m;for (i=0;i<st.size ();i++)if (st[i]=='|') m.push_back (i);i=m.size ()/2;if (i==0) return st;i--;string s=st.substr (m[i]+1,m[i+1]-m[i]-1);b.push_back (fabs (count (s)));num++;st.replace (m[i],m[i+1]-m[i]+1,1,(char) (64+num));if (i!=0) st=abs_cut (st);returnst;}double senior (string str,double x){ int i=0;string s[]={"acos","asin","atan","cos","cosh","sin", "sinh","tan","tanh","ln","log","no"};for (i;i<12;i++) if (str==s[i]) break;switch (i){case 0:return acos (x);case 1:return asin (x);case 2:return atan (x);case 3:return cos (x);case 4:return cosh (x);case 5:return sin (x);case 6:return sinh (x);case 7:return tan (x);case 8:return tanh (x);case 9:return log (x);case 10:return log10 (x);default :cout<<str<<"函数尚未收录\n"; return x;}}。
用c语言编写的计算器源代码
作品:科学计算器作者:欧宗龙编写环境:vc++6.0语言:c#include"stdafx.h"#include<stdio.h>#include<windows.h>#include<windowsx.h>#include"resource.h"#include"MainDlg.h"#include<math.h>#include<string.h>#definePI3.141593BOOLA_Op=FALSE;BOOLWINAPIMain_Proc(HWNDhWnd,UINTuMsg,WPARAMwParam,LPARAMlParam) {switch(uMsg){HANDLE_MSG(hWnd,WM_INITDIALOG,Main_OnInitDialog);HANDLE_MSG(hWnd,WM_COMMAND,Main_OnCommand);HANDLE_MSG(hWnd,WM_CLOSE,Main_OnClose);}returnFALSE;}BOOLMain_OnInitDialog(HWNDhwnd,HWNDhwndFocus,LPARAMlParam){returnTRUE;}voidTrimNumber(chara[])//判断并删除小数点后无用的零{for(unsignedi=0;i<strlen(a);i++){if(a[i]=='.'){for(unsignedj=strlen(a)-1;j>=i;j--){if(a[j]=='0'){a[j]='\0';}elseif(a[j]=='.'){a[j]='\0';}elsebreak;}}}}doubleOperate(charOperator,doublen1,doublen2)//判断符号,进行相应的运算{if(Operator=='0'){}if(Operator=='+'){n2+=n1;}if(Operator=='-'){n2=n1-n2;}if(Operator=='*'){n2*=n1;}if(Operator=='/'){n2=n1/n2;}if(Operator=='^'){n2=pow(n1,n2);}return n2;}////////////////////////////////////////////////voidIntBinary(chara[],intn){if(n>1)IntBinary(a,n/2);sprintf(a,"%s%i",a,n%2);}voiddecimal(chara[],doublem){if(m>0.000001){m=m*2;sprintf(a,"%s%d",a,(long)m);decimal(a,m-(long)m);}}voidBinary(chara[],doubleNum){charDecP[256]="";doublex,y;double*iptr=&y;x=modf(Num,iptr);decimal(DecP,x);IntBinary(a,(int)y);strcat(a,".");strcat(a,DecP);}////////////////////////////////////voidMain_OnCommand(HWNDhwnd,intid,HWNDhwndCtl,UINTcodeNotify) {staticDELTIMES=0;staticcharstr[256];staticcharOperator='0';staticdoubleRNum[3];switch(id){caseIDC_BUTTONN1://数字1{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"1");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN2://数字2{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"2");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN3://数字3{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"3");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN4://数字4{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"4");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN5://数字5{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"5");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN6://数字6{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"6");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN7://数字7{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"7");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN8://数字8{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"8");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN9://数字9{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"9");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN0://数字0{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"0");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));if(DELTIMES==0){strcat(str,".");}DELTIMES++;SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=FALSE;}break;caseIDC_BUTTONADD://加法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='+';DELTIMES=0;A_Op=TRUE;}break;caseIDC_BUTTONSUB://减法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);DELTIMES=0;A_Op=TRUE;Operator='-';}break;caseIDC_BUTTONMUL://乘法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='*';DELTIMES=0;A_Op=TRUE;}break;caseIDC_BUTTONDIV://除法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='/';DELTIMES=0;A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='^';DELTIMES=0;}break;caseIDC_BUTTONPI://圆周率PI,弧度{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));if(atof(str)!=0){RNum[2]=atof(str)*PI;sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);}else{sprintf(str,"%f",PI);SetDlgItemText(hwnd,IDC_EDIT,str);}A_Op=TRUE;}break;caseIDC_BUTTONSQRT://开根号{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=sqrt(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONSIN://三角函数sin函数{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=sin(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=cos(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=tan(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONSQ://平方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str)*atof(str);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str)*atof(str)*atof(str);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=exp(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=pow(10,atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONLN://lnx{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=log(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONLOG10://log10{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=log10(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONBINARY://十进制转换为二进制{chara[256]="";GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str);Binary(a,RNum[2]);strcpy(str,a);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{DELTIMES=0;Operator='0';RNum[0]=RNum[1]=RNum[2]=0;memset(str,0,sizeof(str));SetDlgItemText(hwnd,IDC_EDIT,NULL);A_Op=FALSE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));inti=strlen(str);str[i-1]='\0';SetDlgItemText(hwnd,IDC_EDIT,str);}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='0';DELTIMES=0;}break;default:break;}}voidMain_OnClose(HWNDhwnd){EndDialog(hwnd,0);}本人拙作,如有不足之处请谅解。
C语言计算器源程序
#include<stdio.h>//标准输入输出#include<conio.h>//system设置颜色使用到#include<stdlib.h>//清屏时用到#include<math.h>//数学函数用到int main(){ void mnue();//菜单函数声明void add();//加法函数声明void minus();//减法函数void multiply();//乘法函数void divided();//除法函数void sinx();//sin函数void cosx();//cos函数void tanx();//tan函数void arcsin();//void arccos();void arctan();void sqrtx();void logx();void log10x();void expx();void powx();void tuichu();system("color 5B");mnue();}void mnue()//菜单{ char M;printf("\n\n\n\t\t\t ********* ********\n");printf("\t\t\t ** ** ** **\n");printf("\t\t\t ** ** ** **\n");printf("\t\t\t** 欢迎*** 使用**\n");printf("\t\t\t ** * **\n");printf("\t\t\t ** 简易计算器**\n");printf("\t\t\t ** **\n");printf("\t\t\t.........按任意键进入——》》》\n");printf("\t\t\t ** **\n");printf("\t\t\t ** **\n");printf("\t\t\t ** **\n");printf("\t\t\t *\n");getch();system("cls");while(M!='h'){printf("\n\n\n\t\t\t|------------------------------|\n");printf("\t\t\t| 加法—>A\t| 减法—>a |\n");printf("\t\t\t| 乘法—>B\t| 除法—>b |\n");printf("\t\t\t| 正弦—>C\t| 反正弦—>c |\n");printf("\t\t\t| 余弦—>D\t| 反余弦—>d |\n");printf("\t\t\t| 正切—>E\t| 反正切—>e |\n");printf("\t\t\t| ln —>F\t| log10 —>f |\n");printf("\t\t\t| 幂指数—>G\t| E 幂数—>g |\n");printf("\t\t\t| 开根—>H\t| 退出—>h |\n");printf("\t\t\t|______________________________|\n");printf("\n\t\t请输入要进行运算的法则!\n");M=getch();while(1){if('A'<=M&&M<='H' ||'a'<=M&&M<='h'){ //system("cls");break;}else{printf("\n\n\t提示:输入错误\n\t—>请正确输入!\n\a\a\a\a\a\a\a");M=getch();}}switch(M){case 'A': add();break;case 'a': minus();break;case 'B': multiply();break;case 'b': divided();break;case 'C': sinx();break;case 'c': arcsin();break;case 'D': cosx();break;case 'd': arccos();break;case 'E': tanx();break;case 'e': arctan();break;case 'F': logx();break;case 'f': log10x();break;case 'G': powx();break;case 'g': expx();break;case 'H': sqrtx();break;}}if("M==h") tuichu();}void add()//加法函数{int z, y,x;char n='Y';while(n=='Y'){printf("请输入:\n");scanf("%d%d",&x,&y);z=y+x;printf("%d+%d=%d\n",x,y,z);printf("是否继续(Y/N)\n");n=getch();if(n=='N')system("cls");}}void minus()//减法函数{int x,y,z;char n='Y';while(n=='Y'){printf("请输入:\n");scanf("%d%d",&x,&y);z=x-y;printf("%4d-%4d=%4d\n",x,y,z);printf("是否继续(Y/N)\n");n=getch();if(n=='N')system("cls");}}void multiply()//乘法函数{int x,y,z;char n='Y';while(n=='Y'){printf("请输入:\n");scanf("%d%d",&x,&y);z=x*y;printf("%4d*%4d=%4d\n",x,y,z);printf("是否继续(Y/N)\n");n=getch();if(n=='N')system("cls");}}void divided()//除法函数{float x,y,z;char n='Y';while(n=='Y'){printf("请输入:\n");scanf("%f%f",&x,&y);z=x/y;printf("%4d/%4d=%4d\n",x,y,z);printf("是否继续(Y/N)\n");n=getch();if(n=='N')system("cls");}}void sinx()//sin函数{double x,y;scanf("%lf",&x);y=sin(x);printf("sin%lf=%lf",x,y);}void cosx()//cos函数{double a,b;scanf("%lf",&a);b=cos(a);printf("cos%lf=%lf",b);}void tanx()//tan函数{double a,b;scanf("%lf",&a);b=tan(a);printf("tan%lf=%lf",b);}void arcsin(){double a,b;scanf("%lf",&a);b=asin(a);printf("arcsin%lf=%lf",b);void arccos(){double a,b;scanf("%lf",&a);b=acos(a);printf("arccos%lf=%lf",b); }void arctan(){double a,b;scanf("%lf",&a);b=atan(a);printf("arctan%lf=%lf",b); }void sqrtx(){double a,b;scanf("%lf",&a);b=sqrt(a);printf("sqrt%lf=%lf",b); }void logx(){double a,b;scanf("%lf",&a);b=log(a);printf("log%lf=%lf",a,b); }void log10x(){double a,b;scanf("%lf",&a);b=log10(a);printf("ln%lf=%lf",b);}void expx(){double a,b;scanf("%lf",&a);b=exp(a);printf("exp%lf=%lf\n",b); }void powx()double a,b,c;scanf("%lf%lf",&a,&b);c=pow(a,b);printf("pow%lf=%lf\n",c);}void tuichu(){ system("cls");printf("\n\n\n\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");printf("\n\n\t\t\t谢谢使用再见!\n\n\n");printf("\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n\t"); }。
C语言计算器代码
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,""); 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=='=') {
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; }
} putimage(x,y,rar,XOR_PUT); return;
} void mwindow(char *header) {
int height; cleardevice(); setcolor(MaxColors-1); setviewport(20,20,MaxX,MaxY,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); 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); key=key&0xff?key&0xff:key>>8; return(key);
C编写简易计算器附源代码超详细
超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用Windows窗体应用程序,并命名为Calc,如下图所示:二、向窗体中拖入需要的控件,如下图所示:(完成效果图)结果显示区(作者博客左边的文本框)是TextBox控件,并修改其name为txtShow ,按键0~9为Button控件,并将其name分别修改为btn_0、btn_1、btn_2、btn_3、btn_4、btn_5、btn_6、btn_7、btn_8、btn_9;按键【负数】的name值修改为btn_sign,按键【.】的name 修改为btn_dot,按键【+ - * /】的name值分别修改为btn_add、btn_sub、btn_mul、btn_div,按键【=】的name值修改为btn_equ,按键【倒数】的name值修改为btn_rev,按键【平方】的name值修改为btn_sqr,按键【开方】的name值修改为btn_sqrt。
右边的计算器图片空间是PictureBox,作者博客控件是LinkLabel,可以不添加,以上所有控件均可按照需求添加,只保留自己需要的按钮控件和textbox控件即可。
三、代码部分(含解释),采用switch多分支语句编写using System;using System.Drawing;using System.Collections;using ponentModel;using ;using System.Data;namespace Calc{///<summary>/// QQ:6 温柔一刀C#简易计算器的实现///</summary>public class CalcForm :{private btn_0;private btn_1;private btn_2;private btn_3;private btn_4;private btn_5;private btn_6;private btn_7;private btn_8;private btn_9;private btn_add;private btn_sub;private btn_mul;private btn_div;private btn_sqrt;private btn_sign;private btn_equ;private btn_dot;private btn_rev;private txtShow;private btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;///<summary>///必需的设计器变量。
用C语言写的计算器源代码
用C语言写的计算器源代码#include <stdio.h>#include <conio.h>//用户选择操作符号函数int symint sym;printf("请选择操作符号:1.+ 2.- 3.* 4./ 5.% 6.e(退出)\n");printf("请输入:");scanf("%d", &sym);return sym;//加法函数double add(double a, double b)double c;c=a+b;printf("计算结果:\n");printf("%.2lf + %.2lf = %.2lf", a, b, c);return 0;//减法函数double sub(double a, double b)double c;c=a-b;printf("计算结果:\n");printf("%.2lf - %.2lf = %.2lf", a, b, c); return 0;//乘法函数double mul(double a, double b)double c;c=a*b;printf("计算结果:\n");printf("%.2lf * %.2lf = %.2lf", a, b, c); return 0;//除法函数//判断除数是否为0,为0返回0,反之计算double div(double a, double b)if(b==0)printf("计算错误!");return 0;}elsedouble c;c=a/b;printf("计算结果:\n");printf("%.2lf / %.2lf = %.2lf", a, b, c); return 0;}//取余函数//判断除数是否为0,为0返回0,反之计算int mod(double a, double b)if(b==0)printf("计算错误!");return 0;}elseint c;c=(int)a%(int)b;printf("计算结果:\n");printf("%.0lf %% %.0lf = %d", a, b, c); return 0;}int maindouble a, b;//定义操作符号变量int symbol;//循环计算直到用户选择e(退出)为止while(1)//初始化操作符号变量symbol=0;//输入待计算的两个数printf("请输入待计算的两个数:\n"); scanf("%lf %lf", &a, &b);//调用操作符号函数,获取用户选择symbol=sym(;。
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语言计算器源代码
# 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++语言编写。
#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); /*求表达式值函数声明*/
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
WordListSize=0;
IndexCursor=0;
IndexSize=0;
// Index[=OPER;
printf("Cal>"); //初始化完成,输出提示符
i=0;
while((ch=getchar())!='\n')
case 't':code=11;break; //tg
case 'C':code=12;break; //ctg
case 'l':code=13;break; //log
default:code=-1;break;
};
return code;
{
if(i>MAX) /*输入超长,则出错*/
{
Err(0,i,"输入的表达式长度超过规定值!\n");
isErr=1;
break;
}
if(isupper(ch))
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;
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 */
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, /* ( */
"clr",
"clear",
"window", //窗口模式
"fullscr", //全屏模式
"",
"",
"",
char ch;
num=0.0;
num1=0.0;
num2=0.0;
tempnum=0.0;
Oper=-1;
while(1)
{
for(i=0;i<=MAX;i++) //表达式初始化,中间表索引初始化
{
Expression[i]='\0';
}
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
return i;
}
void help()
int Operator[STACK_SIZE];
int OperStackTop;
double long Number[STACK_SIZE];
int NumStackTop;
double long NumList[STACK_SIZE];
int NumCursor,NumListSize;
Index[i]=-1;
}
for(i=0;i<STACK_SIZE;i++) //操作符栈和数字栈初始化
{
Operator[i]='0';
Number[i]=0.0;
NumList[i]=0.0;
OperList[i]=-1;
int OperList[STACK_SIZE];
int OperCursor,OperListSize;
int WordList[STACK_SIZE];
int WordCursor,WordListSize;
int Index[MAX+1];
int IndexCursor,IndexSize;
char KeyWord[36][WORD_LEN+1]={"sin", //前12个为函数,多余的用于扩展
"cos",
"tan",
"tg",
"ctg",
"lg",
int 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, /* + */
{
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);
"",
"",
"",
"",
"",
""};
int OperCode(char c)
{
WordList[i]=-1;
}
NumStackTop=-1; //栈顶指针初始化
OperStackTop=0; //操作符栈压入\0
Operator[OperStackTop]=OperCode('\0');
#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
"",
"",
"",
"",
"",
"",
"",
"",
"",
"help", // 后面为命令,多余的为扩展
return;
}
double long factorial(int i)
{
if(i==1 || i==0)
return(1.0);
else
return(i*factorial(i-1));
}
main()
{
char Expression[MAX+1];
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 */
#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 lg
case '^':code=5;break;
case '!':code=6;break;
case '(':code=7;break;
case ')':code=8;break;
case 's':code=9;break; //sin
case 'c':code=10;break; //cos
//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
-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 */