C编写简易计算器附源代码超详细
- 格式:doc
- 大小:135.00 KB
- 文档页数:18
#include<stdio.h>#include<math.h>int main(void){int choice,t=1;printf("**********************计算器*****************************************\n"); printf(" 1.加法运算2.减法运算\n"); printf(" 3.乘法运算4.除法运算\n"); printf(" 5.平方运算6.开方运算\n"); printf(" 7.解一元二次方程By:_一念成殇、\n"); printf("**********************************************************************\n");printf("请选择您即将进行的运算方式(输入对应数字):");while(t==1){scanf("%d",&choice);if(choice>7) printf("请您输入正确的选项编号!\n");//加法if(choice==1){float addend_1,addend_2,sum;printf("请输入两个加数:\n");scanf("%f",&addend_1);scanf("%f",&addend_2);sum=addend_1+addend_2;printf("结果为:%.2f",sum);}//减法if(choice==2){float reduction,minuend,difference;printf("请输入被减数和减数:\n");scanf("%f",&reduction);scanf("%f",&minuend );difference=reduction-minuend ;printf("结果为:%.2f",difference);}//乘法if(choice==3){float multiplier_1,multiplier_2,product;printf("请输入两个乘数:\n");scanf("%f",&multiplier_1);scanf("%f",&multiplier_2);product= multiplier_1 * multiplier_2;printf("结果为:%.2f",product);}//除法if(choice==4){float dividend,divisor,conslut;printf("请输入被除数和除数:\n");scanf("%f",÷nd);scanf("%f",&divisor);conslut=dividend/divisor;printf("结果为:%.2f",conslut);}//平方if(choice==5){float base,power;printf("请输入底数:\n");scanf("%f",&base);power=base*base;printf("结果为:%.2f",power);}//开方if(choice==6){float power,base;printf("请输入需要开方的数:\n");scanf("%f",&power);base=sqrt(power);printf("结果为:%.2f",base);}//解一元二次方程if(choice==7){float a,b,c,delta,root_1,root_2;printf("方程一般形式:ax^2+bx+c=0,请输入其中常量a,b,c的值:\n"); scanf("%f",&a);if(a==0){printf("此方程不是一元二次方程!请重新输入!\n");}else{scanf("%f",&b);scanf("%f",&c);delta=(b*b)-(4*a*c);printf("△=%f\n",delta);if(delta<0){printf("此方程无实数根.\n");}else{root_1=(sqrt(delta)-b)/(2.0*a);root_2=((-b)-sqrt(delta))/(2.0*a);printf("解得:x1=%f x2=%f\n",root_1,root_2);}}}printf("\n\n\n\n请选择您即将进行的运算方式(输入对应数字):"); }return 0;}。
简易四则运算计算器计算机工具地历史而言,中国古代最早采用地一种计算工具叫筹策,又叫做算筹,这种算筹多用竹子制成,也有用木头,兽骨充当材料的,大约270枚一束,放在布袋里可随身携带。
直到今天仍在使用的住算盘,是中国古代计算工具领域中的另一项发明明代时的住算盘已经与现代的住算盘几乎相同。
17世纪初,西方国家的计算工具有了较大的发展。
英国数学家纳尔发现了“纳皮尔算筹”;英国牧师奥却德发明了圆柱形对数计算尺,这种计算尺不仅能做加减乘涂,乘方和开方运算,甚至可以计算三角函数,指数函数和对数函数。
这些计算工具不仅带动了计算的发展,也为现代计算器发展尊定了良好的基础,成为现代社会应用广泛的计算工具,如手机,操作系统上附带的多功能计算器。
项目设计目的掌握模块的划分;掌握结构体定义;掌握栈的操作;掌握函数的定义;掌握栈的基本操作;掌握VC的基本绘图库;掌握鼠标的响应操作;目设计内容设计一个含有界面的计算器,输入一个包含括号的表达式,使用栈数据类型实现整数的四则运算操作,开方运算。
项目设计要求根据分析,系统要求实现以下几点基本功能:可通过按钮输入数字、运算符;能通过按钮实现退格、清除功能;实现加、减、乘、除、开方运算功能;实现括号运算;显示运算结果;良好的交互界面。
项目详细设计功能模块图根据系统功能要求,主要含有四大模块,分别是计算器界面设计模块、计算器按键控制模块、四则混合运算模块、计算器记忆处理模块。
计算器界面设计模块:调用VC图形系统函数和字符函数画出计算器的界面,包括24个按钮和一个文本输入框。
计算机按键控制模块:计算器通过键盘按键值的判断,执行相应的操作,如接收数字输入等。
计算器计算处理模块。
计算处理模块主要完成可以包括括号的表达式运算,运算包括加,减,乘,除、开方。
计算处理模块在按键控制模块中被调用执行。
处理模块是通过栈来实现的,分别定义了两个顺序栈,一个用来存放操作符栈,一个用来存放操作数栈。
计算器记忆处理模块。
c语言制作简单的计算器在计算机编程领域中,C语言是一种广泛使用的编程语言之一。
它具有简单易学的特点,并且能够进行复杂的计算和逻辑处理。
今天,我们就来学习一下如何使用C语言来制作一个简单的计算器。
首先,我们需要明确我们计算器的功能和界面设计。
本次制作的计算器将具有基本的四则运算功能,即加法、减法、乘法和除法。
我们将在控制台中实现计算器的操作,并通过简单的用户界面进行交互。
接下来,我们需要创建一个C语言程序的框架。
首先,我们需要包含头文件,以便在程序中使用各种函数和变量。
我们可以使用"#include" 来引入头文件,例如:```c#include <stdio.h>```然后,我们需要定义主函数 `main()`。
在这个函数中,我们将编写计算器的逻辑代码。
让我们开始编写函数吧!首先,我们需要声明一些变量来存储用户输入的数字和运算符。
我们可以使用 `int` 来定义整数变量,并用 `char` 定义字符变量。
例如:```cint num1, num2, result;char operator;```接下来,我们需要提示用户输入要进行的运算,并读取用户输入的数字和运算符。
我们可以使用 `printf` 和 `scanf` 函数来完成这个任务,例如:```cprintf("请输入第一个数字: ");scanf("%d", &num1);printf("请输入运算符(+, -, *, /): ");scanf(" %c", &operator);printf("请输入第二个数字: ");scanf("%d", &num2);```注意,我们在读取运算符之前添加了空格,这是为了消除输入缓冲区中可能残留的换行符等字符。
接下来,我们需要编写代码来进行实际的计算操作。
c语言计算器程序编写代码C语言是一门广泛应用于计算机程序设计中的高级编程语言,计算器是我们日常生活中必不可少的工具之一。
今天,我们将探讨如何使用C语言编写计算器程序。
步骤一:确定计算器的基本功能在开始编写任何计算器程序之前,我们需要先决定它的基本功能。
例如,我们需要让计算器能够执行四种基本算术运算 -- 加、减、乘、除。
我们可能还需要添加其他一些功能,例如计算百分数、开根号、求幂等。
步骤二:编写C语言代码接下来,我们可以开始编写计算器程序的C代码。
此时,我们需要确定程序的最外层框架。
这包括用于接收用户输入、调用所需的函数以及输出结果的代码。
例如,我们可以使用如下的代码框架:```#include <stdio.h>int main() {// 接收输入// 调用对应的函数进行计算// 输出结果return 0;}```步骤三:编写函数我们需要编写函数来执行各种计算。
例如,我们可以编写一个add函数来执行加法,一个Subtract函数来执行减法,以此类推。
对于每个函数,我们需要指定它所需的输入,以及它返回的输出。
例如,对于add函数,我们期望它将两个数字相加,并返回结果:```int add(int x, int y) {return x + y;}```步骤四:解析用户输入为了使计算器程序更加友好,我们希望程序能够解析用户输入并检查其是否有效。
例如,如果用户输入了两个不能相互转换为数字的字符串,则程序应该输出错误消息。
步骤五:测试代码最后,我们需要测试我们的代码以确保它能够正常工作。
这意味着我们应该使用各种输入和边缘情况进行测试,例如“0除以任何数字”和“无效输入”的情况。
总结编写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); /*返回键值*/}。
//计算器,函数#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;}}。
作品:科学计算器作者:欧宗龙编写环境: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);}本人拙作,如有不足之处请谅解。
VC++整理入门计算器本文档是运用VC++6.0整理一个入门计算器的过程。
由于时间和知识技能原因,只能简单的做一个入门级的计算器(只实现加减乘除功能),以后的内容再追加。
一、建立工程启动VC++6.0,然后“文件”新建一个工程,选择“MFC AppWizard(exe)”选项,输入工程名,确定。
(如下图)弹出“MFC应用程序向导-步骤1”选择“基本对话框”,语言选“中文”,点击完成。
在弹出的控件界面,把按钮先删除。
二、设计计算器界面根据自己的喜好设计计算器的界面,(下图是我设计的简易的界面)。
用控件里面的布局计算器的界面,修改按钮显示,先右击要修改的按钮,选择“属性”,修改对应的“标题”。
按钮设计好之后,设置对应的类,加减乘除四个运算符分别如下设置,右击选“建立类向导”,在“Message Maps”选项内,选对应的“IDC_BUTTON1”,设置Messages:BN_CLICKED,然后“Add Function”,一次选择其他三个按钮,按确定。
(如下图)编辑框如下类,同样是右击编辑框,右击选“建立类向导”,选择第二个选项,选择IDC_EDIT1,然后选Add Variable...,在弹出的对话框中名字中输入m_num1,类型选数字Double,对应设置剩下的编辑框,然后确定。
下一步是输入代码。
三、代码的输入双击“+”按钮,然后点击确定,在对应的代码语句中输入下面的语句:void CMyDlg::OnButton1(){UpdateData(1);m_num3=m_num1+m_num2;UpdateData(0);}双击“-”按钮,然后点击确定,在对应的代码语句中输入下面的语句:void CMyDlg::OnButton2(){UpdateData(1);m_num3=m_num1-m_num2;UpdateData(0);}双击“X”按钮,然后点击确定,在对应的代码语句中输入下面的语句:void CMyDlg::OnButton3(){UpdateData(1);m_num3=m_num1*m_num2;UpdateData(0);}双击“/”按钮,然后点击确定,在对应的代码语句中输入下面的语句:void CMyDlg::OnButton4(){UpdateData(1);if(m_num2==0)MessageBox("除数不能为0,请重新输入除数!");elsem_num3=m_num1/m_num2;UpdateData(0);}四:测试到此软件设置完成,运行看看。
C语⾔实现简单计算器程序这两天在看⼀个C语⾔写的计算器程序,做了不少的功夫,跟着作者⼀步步的进⾏完善,了解了许多细节性的东西,在此⾃⼰做个总结,加深⾃⼰对程序的印象,也算是梳理。
在该计算器程序,能进⾏加减乘除、sin、cos、exp等操作,同时能进⾏数值保存功能。
⽽该计算器使⽤逆波兰表⽰法。
即所有运算符都跟在操作数的后⾯,⽐如下列表达式:(1 - 2) * (4 + 5)采⽤逆波兰表⽰法表⽰为:1 2 - 4 5 + *逆波兰表达法中不需要圆括号,只要知道每个运算符需要⼏个操作数就不会引起歧义。
计算器程序实现很简单,具体原理如下:while(/* 下⼀个运算符或操作数不是⽂件结束指⽰符 */)if(/* 是数 */)/* 将该数压⼊到栈中 */else if (/* 是运算符 */)/* 弹出所需数⽬的操作数 *//* 执⾏运算 *//* 将结果压⼊到栈中 */else if (/* 是换⾏符 */)/* 弹出并打印栈顶的值 */else/* 出错 */在程序设计中,使⽤模块化思想,getop函数来进⾏读⼊,该函数返回⼀个标识,⽤来标识读⼊的是什么类型。
主循环体中根据该标识执⾏相应的动作。
以下是该程序:(我将所有函数和变量放在同⼀⽂件)#include <stdlib.h>#include <stdio.h>#include <string.h>#define MAXOP 100#define NUMBER '0' //标识读⼊的是数字#define NAME 'n' //标识读⼊的是字符串(函数名或⾮法字符串)#define ALPHA 26int getop(char []);void push (double); //压栈double pop(void); //出栈void clear(void); //清空栈void mathfnc(char []); //执⾏相应的数学函数sin、cos、exp等int main(void){int type;int i, var = 0;double op1, op2,v;char s[MAXOP];double variable[ALPHA];for (i = 0; i < ALPHA; i++) //初始化⽤于保存数值的变量数组variable[i] = 0.0;while ((type = getop(s)) != EOF) //读取输⼊{switch (type){case NUMBER:push (atof(s));break;case NAME:mathfnc(s);break;case '+':push (pop() + pop());break;case '*':push (pop() * pop());break;case '-':op2 = pop();push (pop() - op2);break;case '/':op2 = pop();if (op2 != 0.0)push (pop() / op2);elseprintf ("error: zero divisor\n");break;case '%':op2 = pop();if (op2 != 0.0)push (fmod(pop(), op2));elseprintf ("error: zero divisor\n");break;case '?': //打印栈顶元素op2 = pop();printf ("\t%.8g\n", op2);push (op2);break;case '=': //保存数值pop();if (var >= 'A' && var <= 'Z')variable[var - 'A'] = pop();elseprintf ("error: no variable name\n");break;case 'c':clear();break;case 'd': //复制栈顶元素op2 = pop();push(op2);push(op2);break;case 's': //交换栈元素op1 = pop();op2 = pop();push(op1);push(op2);case '\n':v = pop(); //v保存最后的⼀次结果printf ("\t%.8g\n", v);break;default:if (type >= 'A' && type <= 'Z')push(variable[type - 'A']);else if (type == '@') //输⼊的字符@表⽰最近⼀次结果值 push(v);elseprintf ("error: unknown command %s\n", s);break;}var = type;}return 0;}/* ----------------------------------------------------------- */#define MAXVAL 100int sp = 0; //标识栈顶double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf ("error: stack full, can't push %g\n", f);}double pop(void){if (sp > 0)return val[--sp];else{printf ("error: statck empty\n");return 0.0;}}void clear(void){sp = 0;}void mathfnc (char s[]){double op2;if (strcmp (s, "sin") == 0)push(sin(pop()));else if(strcmp (s, "cos") == 0)push(cos(pop()));else if(strcmp (s, "exp") == 0)push(exp(pop()));else if(strcmp (s, "pow") == 0){op2 = pop();push (pow(pop(), op2));}elseprintf ("error: %s not supported\n", s);}/* ----------------------------------------------------------- */#include <ctype.h>int getch(void);void ungetch(int);int getop(char s[]){int i, c;while ((s[0] = c = getch()) == ' ' || c == '\t') //过滤开头的空⽩字符;s[1] = '\0';i = 0;if (islower(c)) //判断是否为⼩写字母,也即读取由⼩写字母组成的字符串 {while (islower(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)ungetch(c);if (strlen (s) > 1)return NAME;elsereturn c;}if (!isdigit(c) && c != '.' && c != '-')return c;if (c == '-') //⽤于判断是负数还是减操作{if (isdigit(c = getch()) || c == '.')s[++i] = c;else{if (c != EOF)ungetch(c);return '-';}}if (isdigit(c)) //收集整数部分while (isdigit(s[++i] = c = getch()));if (c == '.') //收集⼩数部分while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)ungetch(c);return NUMBER;}/* ----------------------------------------------------------- *//** 引⽤以下两个函数是因为:程序不能确定它已经读⼊的输⼊是否⾜够 ** 除⾮超前多读⼊⼀些输⼊,在本程序中,读⼊⼀些字符合成⼀个数字 ** 所以在看到第⼀个⾮数字字符之前,已经读⼊的数的完整性是不能确定的* 由于程序要超前读⼊⼀个字符,这样就导致最后⼜⼀个字符不属于当前所要读⼊的数*/#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch (int c){if (bufp >= BUFSIZE)printf ("ungetch: too many characters\n");elsebuf[bufp++] = c;}该程序虽然简单,但是还是存在⼀些⼩⼩的问题,⽐如没有数据时进⾏pop的话,会打印栈中⽆数据同时返回数值0.0,在循环体中许多执⾏操作会将该数值保存到栈中,之后打印该值,⽤户体验度⽐较差。
C语⾔实现简单计算器功能(1)本⽂为⼤家分享了C语⾔实现简单计算器功能的具体⽅法,供⼤家参考,具体内容如下这⼏天⼀直上控制语句,在学完if、switch和循环语句后,为了巩固所学知识点,想给学⽣出⼀道简单的计算器程序。
题⽬如下:通过所学的知识(选择语句、循环语句)完成⼀个简单的计算器编程,要求不许抄袭,只能⽤⾃⼰所学的知识点,不可引⽤⽹上⾃⼰的不懂的程序。
要求的格式如下图:要求以这样的⼀种格式进⾏输出,并能通过选择完成不同的功能。
如:选择1,完成整数相加功能,算完后⼜能回到该页⾯。
经过分析,我简单的写了⼀段代码,代码如下:#include <stdio.h>void main(){while(1) // while循环操作,实现计算机功能提⽰{int a = 0;int x = 0;int y = 0;int result = 0;printf("****欢迎使⽤计算器****\n");printf("[1] 完成两个整数相加\n");printf("[2] 完成两个整数相减\n");printf("[3] 完成两个整数相乘\n");printf("[4] 完成两个整数取整\n");printf("[5] 完成两个整数取余\n");printf("[0] 退出计算器系统\n");printf("请选择:");scanf("%d",&a);if(a < 0 || a > 5) // 判断输⼊的是否在0~5范围内,不在输出错误提⽰{printf("选择有误,请重新选择!\n");continue;}elseif(0 == a) // 当输⼊为0时需要退出系统{printf("欢迎下次使⽤!\n");break;}switch(a) // 使⽤switch语句进⾏对每个功能的具体操作{case 1: // 加法操作printf("请输⼊两个整数:");scanf("%d%d",&x,&y);result = x+y;printf("结果为:%d\n",result);break;case 2: // 减法操作printf("请输⼊两个整数:");scanf("%d%d",&x,&y);result = x-y;printf("结果为:%d\n",result);break;case 3: // 乘法操作printf("请输⼊两个整数:");scanf("%d%d",&x,&y);result = x*y;printf("结果为:%d\n",result);break;case 4: // 取整操作printf("请输⼊两个整数:");scanf("%d%d",&x,&y);result = x/y;printf("结果为:%d\n",result);break;case 5: // 取余操作printf("请输⼊两个整数:");scanf("%d%d",&x,&y);result = x%y;printf("结果为:%d\n",result);break;default:break;}}}这样就能简单完成⼀个两个整数的计算器功能。
这几天在做一个小计算器,经过两天的调试终于算是做完了(可能还有小Bug)。
最多可以到10的15次方。
源代码如下(源码我已经放到Skydrive上了,点这里下载):// CalculatorDlg.cpp : implementation file//#include "stdafx.h"#include "Calculator.h"#include "CalculatorDlg.h"#include "math.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// CAboutDlg dialog used for App AboutDisplay *Pdisplay;class CAboutDlg : public CDialog{public:CAboutDlg();// Dialog Dataenum { IDD = IDD_ABOUTBOX };protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support// Implementationprotected:DECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){}void CAboutDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()// CCalculatorDlg dialogCCalculatorDlg::CCalculatorDlg(CWnd* pParent /*=NULL*/): CDialog(CCalculatorDlg::IDD, pParent), Cal_display(_T("WELCOME")){m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);Pdisplay=new Display(this);}void CCalculatorDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);DDX_Text(pDX, IDC_EDIT1, Cal_display);}BEGIN_MESSAGE_MAP(CCalculatorDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()//}}AFX_MSG_MAP// ON_WM_KEYDOWN()ON_BN_CLICKED(IDOK, &CCalculatorDlg::OnBnClickedOk)ON_BN_CLICKED(IDCANCEL, &CCalculatorDlg::OnBnClickedCancel)ON_BN_CLICKED(IDCANCEL2, &CCalculatorDlg::OnBnClickedCancel2) ON_BN_CLICKED(IDOK4, &CCalculatorDlg::OnBnClickedOk4)ON_BN_CLICKED(IDOK6, &CCalculatorDlg::OnBnClickedOk6)ON_BN_CLICKED(IDOK2, &CCalculatorDlg::OnBnClickedOk2)ON_BN_CLICKED(IDCANCEL3, &CCalculatorDlg::OnBnClickedCancel3) ON_BN_CLICKED(IDOK3, &CCalculatorDlg::OnBnClickedOk3)ON_BN_CLICKED(IDCANCEL4, &CCalculatorDlg::OnBnClickedCancel4) ON_BN_CLICKED(IDCANCEL6, &CCalculatorDlg::OnBnClickedCancel6) ON_BN_CLICKED(IDCANCEL5, &CCalculatorDlg::OnBnClickedCancel5) ON_BN_CLICKED(IDCANCEL8, &CCalculatorDlg::OnBnClickedCancel8) ON_BN_CLICKED(IDCANCEL9, &CCalculatorDlg::OnBnClickedCancel9) ON_BN_CLICKED(IDCANCEL7, &CCalculatorDlg::OnBnClickedCancel7) ON_BN_CLICKED(IDOK5, &CCalculatorDlg::OnBnClickedOk5)ON_BN_CLICKED(IDOK7, &CCalculatorDlg::OnBnClickedOk7)ON_BN_CLICKED(IDCANCEL10, &CCalculatorDlg::OnBnClickedCancel10) ON_BN_CLICKED(IDOK8, &CCalculatorDlg::OnBnClickedOk8)ON_BN_CLICKED(IDCANCEL12, &CCalculatorDlg::OnBnClickedCancel12)ON_BN_CLICKED(IDCANCEL11, &CCalculatorDlg::OnBnClickedCancel11)ON_BN_CLICKED(IDOK9, &CCalculatorDlg::OnBnClickedOk9)ON_BN_CLICKED(IDCANCEL13, &CCalculatorDlg::OnBnClickedCancel13)ON_BN_CLICKED(IDOK10, &CCalculatorDlg::OnBnClickedOk10)ON_BN_CLICKED(IDCANCEL15, &CCalculatorDlg::OnBnClickedCancel15)ON_BN_CLICKED(IDCANCEL14, &CCalculatorDlg::OnBnClickedCancel14)ON_WM_KEYUP()END_MESSAGE_MAP()// CCalculatorDlg message handlersBOOL CCalculatorDlg::OnInitDialog(){CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization herereturn TRUE; // return TRUE unless you set the focus to a control}//--------------------------------------------------------------------------------------------------//void CCalculatorDlg::OnKeyDown(UINT nChar,UINT nRepCnt,UINT nFlags) //{//int a=1;//CDialog::OnKeyDown(nChar, nRepCnt, nFlags);//}//void CCalculatorDlg::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) //{// int a=1;//// CDialog::OnKeyUp(nChar, nRepCnt, nFlags);//}void CCalculatorDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else if(nID==SC_CLOSE){CCalculatorDlg::OnOK();}else{CDialog::OnSysCommand(nID, lParam);}}// If you add a minimize button to your dialog, you will need the code below// to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework.void CCalculatorDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();}}// The system calls this function to obtain the cursor to display while the user drags// the minimized window.HCURSOR CCalculatorDlg::OnQueryDragIcon(){return static_cast<HCURSOR>(m_hIcon);}//------------------------------OnButtonnClicked 部分-------------------------------------------------------------------------void CCalculatorDlg::OnBnClickedOk(){Caldata.CLEAR();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel(){Caldata.MC();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel2() {Caldata.MR();UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk4() {Caldata.KEYIN(1);UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk6() {Caldata.KEYIN(4);UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk2() {Caldata.MM();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel3() {Caldata.MA();UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk3() {Caldata.PN();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel4() {Caldata.ADD();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel6() {Caldata.KEYIN(2);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel5() {Caldata.KEYIN(3);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel8() {Caldata.KEYIN(6);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel9() {Caldata.KEYIN(5);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel7() {Caldata.MINUS();UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk5(){Caldata.Mode_Error=Caldata.SQRT(); UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk7(){Caldata.SQR();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel10() {Caldata.BY();UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk8(){Caldata.KEYIN(7);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel12() {Caldata.KEYIN(8);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel11() {Caldata.KEYIN(9);UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk9(){Caldata.Mode_Error=Caldata.REC(); UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel13() {Caldata.DIV();UpdateDisplay();}void CCalculatorDlg::OnBnClickedOk10() {Caldata.Dot();UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel15() {Caldata.KEYIN(0);UpdateDisplay();}void CCalculatorDlg::OnBnClickedCancel14() {Caldata.Mode_Error=Caldata.EQUAL();UpdateDisplay();}//------------------------------------------Display部分-----------------------------------------------------------------void CCalculatorDlg::UpdateDisplay(){if(!Caldata.Mode_Error){if(!(Caldata.Mode_Dot)){Cal_display.Format(_T("%lf"),Caldata.Data_Display);for(int i=Cal_display.GetLength()-1;i>1;i--) //去掉尾部多余的0,这个方法可共用,可以写成STATIC{if(Cal_display.GetAt(i)=='.')break;if(Cal_display.GetAt(i)=='0')Cal_display.Delete(i);else break;}}else {if(Caldata.Data_Display!=0){int j=0;Cal_display.Format(_T("%lf"),Caldata.Data_Display);for(int i=Cal_display.GetLength()-1;i>1;i--){if(Cal_display.GetAt(i)=='.')break;if(Cal_display.GetAt(i)=='0')Cal_display.Delete(i);else break;}for(int i=Cal_display.GetLength()-1;i>1;i--){ if(Cal_display.GetAt(i)=='.') break;j++;}if(j<=Caldata.Digi_Dot)for(int i=0;i<Caldata.Digi_Dot-j;i++) //小数输入,尾部补0Cal_display.Append(_T("0")); }else{Cal_display.Format(_T("0."));for(int i=0;i<Caldata.Digi_Dot;i++){Cal_display.Append(_T("0"));}}}}else Cal_display.Format(_T("ERROR"));UpdateData(false);}void CCalculatorDlg::ResetDisplay(){}//--------------------------------CALDATA 部分-----------------------------------------------------------Cal_Data::Cal_Data(){Data_Display=0;Data_Remember=0;Data_Last=0;Mode_Remenber=false;Mode_Input=false;Mode_Dot=false;Mode_Error=false;Digi_Dot=0;calaction=Cal_Action::Action_Null;}void Cal_Data::CLEAR(){Data_Display=0;Data_Last=0;Mode_Input=false;Mode_Error=false;Mode_Dot=false;calaction=Cal_Action::Action_Null;}void Cal_Data::MA(){Data_Remember=Data_Remember+Data_Display; }void Cal_Data::MM(){Data_Remember=Data_Remember-Data_Display; }void Cal_Data::MR(){Data_Display=Data_Remember;Mode_Input=false;}void Cal_Data::MC(){Data_Remember=0;Mode_Remenber=false;}void Cal_Data::ADD(){Data_Last=Data_Display;Mode_Dot=Mode_Input=false; calaction=Cal_Action::Action_Add;}void Cal_Data::MINUS(){Data_Last=Data_Display;Mode_Dot=Mode_Input=false;calaction=Cal_Action::Action_Minus;}void Cal_Data::BY(){Data_Last=Data_Display;Mode_Dot=Mode_Input=false;calaction=Cal_Action::Action_By;}void Cal_Data::DIV(){Data_Last=Data_Display;Mode_Dot=Mode_Input=false;calaction=Cal_Action::Action_Divide;}bool Cal_Data::EQUAL(){double TMP;Digi_Dot=0;Mode_Dot=false;switch(calaction){case Cal_Action::Action_Add : Data_Display+=Data_Last; Mode_Dot=Mode_Input=false;break;case Cal_Action::Action_Minus: Data_Display=Data_Last-Data_Display;Mode_Dot=Mode_Input=false;break;case Cal_Action::Action_By: Data_Display*=Data_Last;Mode_Dot=Mode_Input=false;break;case Cal_Action::Action_Divide: if(Data_Display==0)return true;else Data_Display=Data_Last/Data_Display;Mode_Dot=Mode_Input=false;break;case Cal_Action::Action_Null: Mode_Dot=Mode_Input=false;break;}calaction=Cal_Action::Action_Null;return false;}void Cal_Data::SQR(){Data_Display*=Data_Display;Mode_Dot=Mode_Input=false;}bool Cal_Data::SQRT(){Mode_Dot=Mode_Input=false;if(Data_Display<0)return true;Data_Display=sqrt(Data_Display);return false;}bool Cal_Data::REC(){Mode_Dot=Mode_Input=false;if(Data_Display==0)return true;else Data_Display=1/Data_Display;return false;}void Cal_Data::PN(){if(Data_Display!=0) Data_Display=-Data_Display;}void Cal_Data::Dot(){if(!Mode_Dot) { Mode_Dot=true;Digi_Dot=0;}}void Cal_Data::KEYIN(int value){ if(Data_Display>=100000000000000) //double型的数大于100000000000000后精度不高,所以限定为15位return;if(!Mode_Input){ Mode_Input=true;Data_Display=0;}if(!Mode_Dot){Data_Display*=10.0;Data_Display=Data_Display>=0? Data_Display+(double)value: Data_Display-(double)value;}else{if(Digi_Dot>=6) //小数点后面最多输入到第6位,否者会出错(double的精度不高)return;Digi_Dot++;double TMP=value;for(int i=0;i<Digi_Dot;i++){TMP=TMP/10.0;}Data_Display=Data_Display>=0? Data_Display+TMP:Data_Display-TMP;。
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;}}//主循环结束}//主函数结束。
超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用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>int maichar operator;double num1, num2;printf("请输入运算符:");scanf("%c", &operator);printf("请输入两个数字:");scanf("%lf %lf", &num1, &num2);switch (operator)case '+':printf("%.2lf + %.2lf = %.2lf", num1, num2, num1 + num2); break;case '-':printf("%.2lf - %.2lf = %.2lf", num1, num2, num1 - num2); break;case '*':printf("%.2lf * %.2lf = %.2lf", num1, num2, num1 * num2);break;case '/':if (num2 != 0)printf("%.2lf / %.2lf = %.2lf", num1, num2, num1 / num2);elseprintf("除数不能为0");break;default:printf("无效的运算符");}return 0;```这个程序首先提示用户输入一个运算符,然后再提示输入两个数字。
接下来,程序会根据输入的运算符执行相应的计算,并打印结果。
在计算除法时,程序会检查除数是否为0,如果为0,则打印错误信息。
请注意,这只是一个非常简单的计算器程序,没有考虑很多错误处理情况。
超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用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;usingusing System.Data;namespace Calc{///<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>///必需的设计器变量。
///</summary>private ponentModel.Container components=null;public CalcForm(){////Windows窗体设计器支持所必需的//InitializeComponent();////TODO:在InitializeComponent调用后添加任何构造函数代码//}///<summary>///清理所有正在使用的资源。
///</summary>protectedoverridevoid Dispose(bool disposing){if(disposing){if(components!=null){components.Dispose();}}base.Dispose(disposing);}#region WindowsFormDesignergeneratedcode///<summary>///设计器支持所需的方法-不要使用代码编辑器修改///此方法的内容。
///</summary>privatevoid InitializeComponent(){ponentResourceManager resources=new ponentRe sourceManager(typeof(CalcForm));this.btn_9=new Button();this.txtShow=new TextBox();this.btn_8=new Button();this.btn_7=new Button();this.btn_div=new Button();this.btn_sqrt=new Button();this.btn_4=new Button();this.btn_5=new Button();this.btn_6=new Button();this.btn_1=new Button();this.btn_2=new Button();this.btn_3=new Button();this.btn_0=new Button();this.btn_mul=new Button();this.btn_sub=new Button();this.btn_sign=new Button();this.btn_equ=new Button();this.btn_add=new Button();this.btn_dot=new Button();this.btn_sqr=new Button();this.btn_rev=new Button();this.pictureBox1=new PictureBox();this.linkLabel1=new LinkLabel();((ponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();this.SuspendLayout();////btn_9//this.btn_9.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_9.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_9.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_9.ForeColor=System.Drawing.Color.Black;this.btn_9.Location=new System.Drawing.Point(126,37);this.btn_="btn_9";this.btn_9.Size=new System.Drawing.Size(59,31);this.btn_9.TabIndex=0;this.btn_9.Tag="9";this.btn_9.Text="9";this.btn_eVisualStyleBackColor=false;this.btn_9.Click+=new System.EventHandler(this.btn_0_Click);////txtShow//this.txtShow.Location=new System.Drawing.Point(4,6);="txtShow";this.txtShow.ReadOnly=true;this.txtShow.Size=new System.Drawing.Size(242,21);this.txtShow.TabIndex=1;this.txtShow.TextAlign=HorizontalAlignment.Right;////btn_8//this.btn_8.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_8.BackgroundImageLayout=ImageLayout.Center;this.btn_8.FlatAppearance.MouseDownBackColor=System.Drawing.SystemColors.ButtonFace; this=System.Drawing.Color.WhiteSmoke;this.btn_8.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_8.ForeColor=System.Drawing.Color.Black;this.btn_8.Location=new System.Drawing.Point(66,37);this.btn_="btn_8";this.btn_8.Size=new System.Drawing.Size(59,31);this.btn_8.TabIndex=2;this.btn_8.Tag="8";this.btn_8.Text="8";this.btn_eVisualStyleBackColor=false;this.btn_8.Click+=new System.EventHandler(this.btn_0_Click);////btn_7//this.btn_7.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_7.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_7.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_7.ForeColor=System.Drawing.Color.Black;this.btn_7.Location=new System.Drawing.Point(4,37);this.btn_="btn_7";this.btn_7.Size=new System.Drawing.Size(59,31);this.btn_7.TabIndex=3;this.btn_7.Tag="7";this.btn_7.Text="7";this.btn_eVisualStyleBackColor=false;this.btn_7.Click+=new System.EventHandler(this.btn_0_Click);////btn_div//this.btn_div.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_div.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_div.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_div.ForeColor=System.Drawing.Color.Red;this.btn_div.Location=new System.Drawing.Point(187,37);this.btn_="btn_div";this.btn_div.Size=new System.Drawing.Size(59,31);this.btn_div.TabIndex=4;this.btn_div.Text="/";this.btn_eVisualStyleBackColor=false;this.btn_div.Click+=new System.EventHandler(this.btn_div_Click);////btn_sqrt//this.btn_sqrt.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_sqrt.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_sqrt.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_sqrt.ForeColor=System.Drawing.Color.Black;this.btn_sqrt.Location=new System.Drawing.Point(253,37);this.btn_="btn_sqrt";this.btn_sqrt.Size=new System.Drawing.Size(59,31);this.btn_sqrt.TabIndex=5;this.btn_sqrt.Text="开方";this.btn_eVisualStyleBackColor=false;this.btn_sqrt.Click+=new System.EventHandler(this.btn_sqrt_Click);////btn_4//this.btn_4.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_4.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_4.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_4.ForeColor=System.Drawing.Color.Black;this.btn_4.Location=new System.Drawing.Point(4,72);this.btn_="btn_4";this.btn_4.Size=new System.Drawing.Size(59,31);this.btn_4.TabIndex=6;this.btn_4.Tag="4";this.btn_4.Text="4";this.btn_eVisualStyleBackColor=false;this.btn_4.Click+=new System.EventHandler(this.btn_0_Click);////btn_5//this.btn_5.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_5.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_5.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_5.ForeColor=System.Drawing.Color.Black;this.btn_5.Location=new System.Drawing.Point(66,72);this.btn_="btn_5";this.btn_5.Size=new System.Drawing.Size(59,31);this.btn_5.TabIndex=7;this.btn_5.Tag="5";this.btn_5.Text="5";this.btn_eVisualStyleBackColor=false;this.btn_5.Click+=new System.EventHandler(this.btn_0_Click);////btn_6//this.btn_6.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_6.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_6.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_6.ForeColor=System.Drawing.Color.Black;this.btn_6.Location=new System.Drawing.Point(126,72);this.btn_="btn_6";this.btn_6.Size=new System.Drawing.Size(59,31);this.btn_6.TabIndex=8;this.btn_6.Tag="6";this.btn_6.Text="6";this.btn_eVisualStyleBackColor=false;this.btn_6.Click+=new System.EventHandler(this.btn_0_Click);////btn_1//this.btn_1.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_1.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_1.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_1.ForeColor=System.Drawing.Color.Black;this.btn_1.Location=new System.Drawing.Point(4,108);this.btn_="btn_1";this.btn_1.Size=new System.Drawing.Size(59,31);this.btn_1.TabIndex=9;this.btn_1.Tag="1";this.btn_1.Text="1";this.btn_eVisualStyleBackColor=false;this.btn_1.Click+=new System.EventHandler(this.btn_0_Click);////btn_2//this.btn_2.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_2.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_2.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_2.ForeColor=System.Drawing.Color.Black;this.btn_2.Location=new System.Drawing.Point(66,108);this.btn_="btn_2";this.btn_2.Size=new System.Drawing.Size(59,31);this.btn_2.TabIndex=10;this.btn_2.Tag="2";this.btn_2.Text="2";this.btn_eVisualStyleBackColor=false;this.btn_2.Click+=new System.EventHandler(this.btn_0_Click);////btn_3//this.btn_3.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_3.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_3.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_3.ForeColor=System.Drawing.Color.Black;this.btn_3.Location=new System.Drawing.Point(126,108);this.btn_="btn_3";this.btn_3.Size=new System.Drawing.Size(59,31);this.btn_3.TabIndex=11;this.btn_3.Tag="3";this.btn_3.Text="3";this.btn_eVisualStyleBackColor=false;this.btn_3.Click+=new System.EventHandler(this.btn_0_Click);////btn_0//this.btn_0.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_0.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_0.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_0.ForeColor=System.Drawing.Color.Black;this.btn_0.Location=new System.Drawing.Point(4,143);this.btn_="btn_0";this.btn_0.Size=new System.Drawing.Size(59,31);this.btn_0.TabIndex=12;this.btn_0.Tag="0";this.btn_0.Text="0";this.btn_eVisualStyleBackColor=false;this.btn_0.Click+=new System.EventHandler(this.btn_0_Click);////btn_mul//this.btn_mul.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_mul.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_mul.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_mul.ForeColor=System.Drawing.Color.Red;this.btn_mul.Location=new System.Drawing.Point(187,72);this.btn_="btn_mul";this.btn_mul.Size=new System.Drawing.Size(59,31);this.btn_mul.TabIndex=13;this.btn_mul.Text="*";this.btn_eVisualStyleBackColor=false;this.btn_mul.Click+=new System.EventHandler(this.btn_mul_Click);////btn_sub//this.btn_sub.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_sub.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_sub.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_sub.ForeColor=System.Drawing.Color.Red;this.btn_sub.Location=new System.Drawing.Point(187,108);this.btn_="btn_sub";this.btn_sub.Size=new System.Drawing.Size(59,31);this.btn_sub.TabIndex=14;this.btn_sub.Text="-";this.btn_eVisualStyleBackColor=false;this.btn_sub.Click+=new System.EventHandler(this.btn_sub_Click);////btn_sign//this.btn_sign.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_sign.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_sign.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_sign.ForeColor=System.Drawing.Color.Red;this.btn_sign.Location=new System.Drawing.Point(66,143);this.btn_="btn_sign";this.btn_sign.Size=new System.Drawing.Size(59,31);this.btn_sign.TabIndex=15;this.btn_sign.Text="负数";this.btn_eVisualStyleBackColor=false;this.btn_sign.Click+=new System.EventHandler(this.btn_sign_Click);////btn_equ//this.btn_equ.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_equ.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_equ.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_equ.ForeColor=System.Drawing.Color.Red;this.btn_equ.Location=new System.Drawing.Point(253,143);this.btn_="btn_equ";this.btn_equ.Size=new System.Drawing.Size(59,31);this.btn_equ.TabIndex=16;this.btn_equ.Text="=";this.btn_eVisualStyleBackColor=false;this.btn_equ.Click+=new System.EventHandler(this.btn_equ_Click);////btn_add//this.btn_add.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_add.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_add.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_add.ForeColor=System.Drawing.Color.Red;this.btn_add.Location=new System.Drawing.Point(187,143);this.btn_="btn_add";this.btn_add.Size=new System.Drawing.Size(59,31);this.btn_add.TabIndex=17;this.btn_add.Text="+";this.btn_eVisualStyleBackColor=false;this.btn_add.Click+=new System.EventHandler(this.btn_add_Click);////btn_dot//this.btn_dot.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_dot.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_dot.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_dot.ForeColor=System.Drawing.Color.Black;this.btn_dot.Location=new System.Drawing.Point(126,143);this.btn_="btn_dot";this.btn_dot.Size=new System.Drawing.Size(59,31);this.btn_dot.TabIndex=18;this.btn_dot.Text=".";this.btn_eVisualStyleBackColor=false;this.btn_dot.Click+=new System.EventHandler(this.btn_dot_Click);////btn_sqr//this.btn_sqr.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_sqr.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_sqr.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_sqr.ForeColor=System.Drawing.Color.Black;this.btn_sqr.Location=new System.Drawing.Point(253,72);this.btn_="btn_sqr";this.btn_sqr.Size=new System.Drawing.Size(59,31);this.btn_sqr.TabIndex=19;this.btn_sqr.Text="平方";this.btn_eVisualStyleBackColor=false;this.btn_sqr.Click+=new System.EventHandler(this.btn_sqr_Click);////btn_rev//this.btn_rev.BackColor=System.Drawing.SystemColors.ActiveBorder;this.btn_rev.BackgroundImageLayout=ImageLayout.Center;this=System.Drawing.SystemColors.ButtonFace;this=System.Drawing.Color.WhiteSmoke;this.btn_rev.Font=new System.Drawing.Font("黑体",10.5F,System.Drawing.FontStyle.Bold,System.Drawing.GraphicsUnit.Point,((byte)(134))); this.btn_rev.ForeColor=System.Drawing.Color.Red;this.btn_rev.Location=new System.Drawing.Point(253,108);this.btn_="btn_rev";this.btn_rev.Size=new System.Drawing.Size(59,31);this.btn_rev.TabIndex=20;this.btn_rev.Text="倒数";this.btn_eVisualStyleBackColor=false;this.btn_rev.Click+=new System.EventHandler(this.btn_rev_Click);////pictureBox1//this.pictureBox1.Image=((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location=new System.Drawing.Point(319,6);="pictureBox1";this.pictureBox1.Size=new System.Drawing.Size(100,168);this.pictureBox1.TabIndex=21;this.pictureBox1.TabStop=false;////linkLabel1//this.linkLabel1.AutoSize=true;this.linkLabel1.Location=new System.Drawing.Point(253,13);="linkLabel1";this.linkLabel1.Size=new System.Drawing.Size(53,12);this.linkLabel1.TabIndex=22;this.linkLabel1.TabStop=true;this.linkLabel1.Text="作者博客";this.linkLabel1.LinkClicked+=new LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked );////CalcForm//this.AutoScaleBaseSize=new System.Drawing.Size(6,14);this.ClientSize=new System.Drawing.Size(427,181);this.Controls.Add(this.linkLabel1);this.Controls.Add(this.pictureBox1);this.Controls.Add(this.btn_rev);this.Controls.Add(this.btn_sqr);this.Controls.Add(this.btn_dot);this.Controls.Add(this.btn_add);this.Controls.Add(this.btn_equ);this.Controls.Add(this.btn_sign);this.Controls.Add(this.btn_sub);this.Controls.Add(this.btn_mul);this.Controls.Add(this.btn_0);this.Controls.Add(this.btn_3);this.Controls.Add(this.btn_2);this.Controls.Add(this.btn_1);this.Controls.Add(this.btn_6);this.Controls.Add(this.btn_5);this.Controls.Add(this.btn_4);this.Controls.Add(this.btn_sqrt);this.Controls.Add(this.btn_div);this.Controls.Add(this.btn_7);this.Controls.Add(this.btn_8);this.Controls.Add(this.txtShow);this.Controls.Add(this.btn_9);this.FormBorderStyle=FormBorderStyle.FixedDialog;this.MaximizeBox=false;="CalcForm";this.StartPosition=FormStartPosition.CenterScreen;this.Text="C#编写计算器by";this.Load+=new System.EventHandler(this.CalcForm_Load);((ponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false);this.PerformLayout();}#endregionpublicconstint NULL=0; //定义操作码publicconstint ADD=1;publicconstint SUB=2;publicconstint MUL=3;publicconstint DIV=4;publicconstint SQR=5;publicconstint SQRT=6;publicconstint NODOT=0; //定义是否点击了小数点publicconstint HASDOT=1;privatedouble res=0; //记录结果数privatedouble tmp=0; //当前输入的操作数privateint opt=NULL; //记录操作码privateint dot=NODOT; //记录是否点击了小数点privateint num=0; //记录输入操作数的个数privateint dotnum=0; //记录小数点部分的个数///<summary>///应用程序的主入口点。