大学计算机C++语言计算器源代码

合集下载

c语言计算器代码

c语言计算器代码

}
}
}
void jianfa()
{
int a,b,c,l;
printf("您现在即将使用减法器^-^\n");
printf("请输入两个数吧^-^\n");
scanf("%d%d",&a,&b);
c=a-b;
printf("您输入的两个数是%d %d\n",a,b);
p=m+x;
q=n+y;
printf("%d+%di+%d+%di=%d+%di\n",m,n,x,y,p,q);
break;
c=p;
t=q;
case 4:l=0;break;
printf("%d/%d=%d\n",a,b,c);
}
void caozuo()
{ int a,p;
p=1;
printf("您使用的是两位数计算器\n");
printf("1表示加法\n2表示减法\n3表示乘法\n4表示除法\n5表示退出\n");
while(p)
{
scanf("%d",&r);
switch(r)
{
case 1:printf("请继续输入一个数吧\n");
scanf("%d",&m);
n=c-m;
printf("%d-%d=%d\n",c,m,n);
}
}
}

简单计算器c语言源码

简单计算器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  语言)实现源代码

计算器(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语言用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语言编写的计算器源代码

用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>#define PI 3.141593BOOL A_Op=FALSE;BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {switch(uMsg){HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);HANDLE_MSG(hWnd, WM_MAND, Main_Onmand);HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);}return FALSE;}BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam){return TRUE;}void TrimNumber(char a[])//判断并删除小数点后无用的零for(unsigned i=0;i<strlen(a);i++){if(a[i]=='.'){for(unsigned j=strlen(a)-1;j>=i;j--){if(a[j]=='0'){a[j]='\0';}else if(a[j]=='.'){a[j]='\0';}else break;}}}}double Operate(char Operator,double n1,double n2) //判断符号,进行相应的运算{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;}////////////////////////////////////////////////void IntBinary(char a[],int n){if(n>1)IntBinary(a,n/2);sprintf(a,"%s%i",a,n%2);}void decimal(char a[],double m){if(m>0.000001){m=m*2;sprintf(a,"%s%d",a,(long)m);decimal(a,m-(long)m);}}void Binary(char a[],double Num){char DecP[256]="";double x,y;double *iptr=&y;x=modf(Num,iptr);decimal(DecP,x);IntBinary(a,(int)y);strcat(a,".");strcat(a,DecP);}////////////////////////////////////void Main_Onmand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) {static DELTIMES=0;static char str[256];static char Operator='0';static double RNum[3];switch(id){case IDC_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;case IDC_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;case IDC_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;case IDC_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;case IDC_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;case IDC_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;case IDC_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;case IDC_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;case IDC_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;case IDC_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 IDC_BUTTONDEL://小数点.del{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;case IDC_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;case IDC_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;case IDC_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;case IDC_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 IDC_BUTTONXY://x的y次方{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;case IDC_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;case IDC_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;case IDC_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 IDC_BUTTONCOS://三角函数cos函数{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 IDC_BUTTONTAN://三角函数tan函数{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;case IDC_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 IDC_BUTTONCUBE://三次方{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 IDC_BUTTONEX://e的x次方{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 IDC_BUTTON10X://10的x次方{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;case IDC_BUTTONLN: //ln x{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;case IDC_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;case IDC_BUTTONBINARY: //十进制转换为二进制{char a[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 IDC_BUTTONCLEAR://清除数据{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 IDC_BUTTONBACKSPACE://退格键{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));int i=strlen(str);str[i-1]='\0';SetDlgItemText(hwnd,IDC_EDIT,str);}break;case IDC_ENTER://Enter键{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;}}void Main_OnClose(HWND hwnd){EndDialog(hwnd, 0);}本人拙作,如有不足之处请谅解。

C语言计算器源程序

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语言计算器代码

C语言计算器代码
printf("西安工程大学计算机01班...本程序目标:简单计算器\n\n");Sleep(1000);
printf("小组组长:");Sleep(1000);
puts("尹化荣\n");Sleep(300);
printf("小组成员:");Sleep(300);
printf("尹化荣,");Sleep(300);
{
COORD coord;
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), coord );
}
void hidden()//隐藏光标
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
//------------------------------------------------------------------||
//迷宫游戏,所有声明:
#define Height 23 //迷宫的高度,必须为奇数
#define Width 39 //迷宫的宽度,必须为奇数
#define Wall 1
double jiafa(double a,double b);
double jianfa(double a,double b);
double chengfa(double a,double b);
double chufa(double a,double b);
intqiuyu(int a,int b);
CONSOLE_CURSOR_INFO cci;

C编写简易计算器附源代码超详细

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语言写的计算器源代码

用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语⾔计算器程序源代码//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语言编写的计算器代码附带使用说明

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语言计算器源代码

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编写简易计算器附源代码超详细

超详细因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用Win dows窗体应用程序,并命名为Calc,如下图所示:向窗体中拖入需要的控件,如下图所示:结果显示区(作者博客左边的文本框)是TextBox控件,并修改其name为txtShow,按键0~9 为Button 控件,并将其name分别修改为btn_O、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;usingusing System.Data;namespaceCalc{///<summary>///温柔一刀C#简易计算器的实现///</summary>publicclass CalcForm: Form{private Button btn_0; private Button btn_1; private Button btn_2; private Button btn_3;private Button btn_4;private Button btn_5;private Button btn_6;private Button btn_7;private Button btn_8;private Button btn_9;private Button btn_add;private Button btn_sub;private Button btn_mul;private Button btn_div;private Button btn_sqrt;private Button btn_sign;private Button btn_equ;private Button btn_dot;private Button btn_rev;private TextBox txtShow;private Button btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;///<summary>/// 必需的设计器变量。

C语言计算器源代码

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语言 计算器 源代码

C语言 计算器 源代码
setcolor(BLUE); /*设置蓝色模式*/
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. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C++语言编写。

#include<iostream>#include<cmath>#include<string>using namespace std;const double pi = 3.14159265;const double e = 2.718281828459;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;}。

相关文档
最新文档