简易计算器程序源代码
简易计算器程序源代码
简易计算器程序源代码下面是一个简易计算器程序的源代码,它可以执行基本的四则运算:```python#定义加法函数def add(x, y):return x + y#定义减法函数def subtract(x, y):return x - y#定义乘法函数def multiply(x, y):return x * y#定义除法函数def divide(x, y):if y == 0:return "除数不能为0"else:return x / y#显示菜单print("选择操作:")print("1. 相加")print("2. 相减")print("3. 相乘")print("4. 相除")#获取用户输入choice = input("输入你的选择(1/2/3/4): ")#获取用户输入的两个数字num1 = float(input("输入第一个数字: "))num2 = float(input("输入第二个数字: "))#根据用户选择执行相应操作if choice == '1':print(num1, "+", num2, "=", add(num1, num2))elif choice == '2':print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3':print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4':print(num1, "/", num2, "=", divide(num1, num2))else:print("请输入有效的选择")```运行这个程序,你将看到一个简易的计算器菜单。
单片机简易计算器程序代码
else{write_com(0x01);write_date(0x41) ;write_date(0x4e);write_date(0x53);write_date(0x30+i);a=daan;gz=gz+4;}
{fuhao=3;i=table1[num];if(eq==0){gz++; write_date(0x30+i);}
else {write_com(0x01);write_date(0x41) ;write_date(0x4e);write_date(0x53);write_date(0x30+i);a=daan;gz=gz+4;}
}//3表示乘号已按
if(g==1)
{g=0;gg(gz);fuhao=6;if(eq==0){gz=gz+3;write_date(0x43);write_date(0x4f);write_date(0x53);}
else{write_com(0x01);write_date(0x43);write_date(0x4f);write_date(0x53);write_date(0x4e);write_date(0x41) ;write_date(0x4e);write_date(0x53);b=daan;gz=gz+6;}
if(g==0)
{
write_com(0x01);
a=0;
b=0;
flag=0;
fuhao=0;
eq=0;
ad=0;bd=0;afd=0;bfd=0;
简单计算器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';}。
简易计算器代码
button[10] = new QPushButton(buttontext[10],this,buttontext[10]); // “—”
button[10]->setFixedSize(BUTTONWIDTH,BUTTONHEIGHT);
edit->setText(tr("%1").arg(0)); //这个函数可获取文本编辑框中光标的位置,并显示在状态栏中
//setText(tr(“%1行%2列”).arg(rowNum).arg(colNum));
initialize(); //调用初始化函数
}
void CWidget::initialize()
cwidget.cpp
#include "cwidget.h"
#define KEY_CLR "CLR"
#define KEY_ADD "+"
#define KEY_SUB "-"
#define KEY_MUL "*"
#define KEY_DIV "/"
#define KEY_EQ "="
#define KEY_0 "0"
{
delete edit;
delete *button;
delete mainLayout;
delete topLayout;
delete bottomLayout;
}
void CWidget::calculate() //响应按键“=”,调用计算功能
计算器编程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); /*返回键值*/}。
简单计算器源代码
static Button b3=new Button("9");
static Button b4=new Button("/");
static Button b5=new Button("Close");
static Button C1=new Button("4");
{
int z=a.length();
int q1=a.indexOf("+");
int q2=a.indexOf("/");
int q3=a.indexOf("-");
int q4=a.indexOf("*");
if(q2>0)
}
if(q4>0)
{
String c=a.substring(0,q4);
float c1=Float.parseFloat(c);
String d=a.substring(q4+1);
String d=a.substring(q3+1);
float d1=Float.parseFloat(d);
float sum=c1-d1;
tf.setText(""+sum);
a=""+sum;
if(e.getSource()==C1)
a+="4";
if(e.getSource()==D1)
a+="1";
python科学计算器代码
python科学计算器代码Python科学计算器是一种功能强大的工具,可以用于进行各种科学和数学计算。
它可以进行基本的算术运算,如加减乘除,还可以进行更复杂的计算,如指数、对数、三角函数等。
科学计算器还可以处理大型数据集和矩阵运算,进行数据分析和可视化等。
下面是一个简单的Python科学计算器代码示例。
```pythonimport mathdef add(x, y):return x + ydef subtract(x, y):return x - ydef multiply(x, y):return x * ydef divide(x, y):return x / ydef exponentiation(x, y):return x ** ydef logarithm(x, base):return math.log(x, base)def square_root(x):return math.sqrt(x)def sine(x):return math.sin(math.radians(x))def cosine(x):return math.cos(math.radians(x))def tangent(x):return math.tan(math.radians(x))# 用户输入操作符和操作数operator = input("Enter an operator (+, -, *, /, **, log, sqrt, sin, cos, tan): ")while operator not in ['+', '-', '*', '/', '**', 'log', 'sqrt', 'sin', 'cos', 'tan']: operator = input("Invalid operator. Please enter a valid operator (+, -, *, /, **, log, sqrt, sin, cos, tan): ")if operator in ['+', '-', '*', '/']:num1 = float(input("Enter the first number: "))num2 = float(input("Enter the second number: "))if operator == '+':result = add(num1, num2)elif operator == '-':result = subtract(num1, num2)elif operator == '*':result = multiply(num1, num2)else:result = divide(num1, num2)elif operator in ['**', 'log', 'sqrt', 'sin', 'cos', 'tan']:num = float(input("Enter a number: "))if operator == '**':exponent = float(input("Enter an exponent: "))result = exponentiation(num, exponent)elif operator == 'log':base = float(input("Enter a base: "))result = logarithm(num, base)elif operator == 'sqrt':result = square_root(num)elif operator == 'sin':result = sine(num)elif operator == 'cos':result = cosine(num)else:result = tangent(num)print("Result:", result)```这个代码示例中,我们定义了一系列的函数来执行各种不同的计算操作。
编写简易计算器附源代码超详细
超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用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>public class CalcFormForm{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>///必需的设计器变量。
简易计算器源代码
基于S3C2410 ARM9 的计算器小程序,下面是源代码。
以及7279 接口和相应的驱动程序。
#include "2410addr.h"//加载地址一些最基本的地址#include <string.h>#include "7279.h"//7279控制数码管和键盘的int counter=0,operation=0,edge=0;//counter是用来计算你输入的次数的你琽peration 用来判断是否有intkey_number1=0,key_number2=0,key_number3=0,key_number=0,math=0,out_bit[6] ,yes_key=0; int allnumber[20];void result(){int n=counter-1;int i=0;key_number1=0;key_number2=0;key_number3=0;for(i=0;i<edge-1;i++)key_number1= (key_number1*10+allnumber[i]);for(i=edge;i<=n;i++)key_number2= (key_number2*10+allnumber[i]);i=edge-1;switch(allnumber[i]){case 10: key_number3 = key_number1 + key_number2;break;case 11: key_number3 = key_number1 - key_number2;break;case 12: key_number3 = key_number1 * key_number2;break;case 13: key_number3 = key_number1 / key_number2;break;}for(i=0;i<6;i++){out_bit[i]= key_number3%0x0a;key_number3 = key_number3/0x0a;write7279(DECODE1+i,out_bit[i]);}}void __irq Keyaddnumb(void){yes_key=1;rINTMSK|=(BIT_EINT2);//key_number=read7279(CMD_READ);key_number=read7279(CMD_READ);ClearPending(BIT_EINT2); //清除中断标志rINTMSK&=~(BIT_EINT2);//yes_key=0;}void Main(){int j=0;Init7279();//EINT2 RiserGPFCON = (rGPFCON&0xff0f)|0x0060; //GPF2:Interrupt;GPF3:Out 7279CS //extern int p=0;//for(p=0;p<20;p++)allnumber[p]=0;send_byte(CMD_RESET);write7279(0x98,0xff);rEXTINT0= (rEXTINT0&0xffff00FF)|0x00000400; pISR_EINT2=(unsigned)Keyaddnumb; rINTMOD=0x0; //设置为IRQ模式rINTMSK&=~(BIT_EINT2); //打开keyboard中断do{if(yes_key==1){switch(key_number){case 0x03: key_number = 0;operation=0;break; case 0x0b: key_number = 1;operation=0;break; case 0x13: key_number = 2;operation=0;break; case 0x1b: key_number = 3;operation=0;break; case 0x04: key_number = 4;operation=0;break; case 0x0c: key_number = 5;operation=0;break; case 0x14: key_number = 6;operation=0;break; case 0x1c: key_number = 7;operation=0;break; case 0x05: key_number = 8;operation=0;break; case 0x0d: key_number = 9;operation=0;break; case 0x15: key_number = 10;operation=1;break; case 0x1d: key_number = 11;operation=2;break; case 0x06: key_number = 12;operation=3;break; case 0x0e: key_number = 13;operation=4;break; case 0x16: key_number = 14;operation=5;break;case 0x1e: key_number = 15;operation=6;break; } if(key_number==14) { result(); for(j=0;j<19;j++) allnumber[j]=0; counter=0;edge=0; } else if(key_number ==15) { // while(1){ //for(j=0;j<1000000;j++)short_delay(); send_byte(CMD_RESET); } /*Init7279();//EINT2 Rise rGPFCON = (rGPFCON&0xff0f)|0x0060;//GPF2:Interrupt;GPF3:Out 7279CS rEXTINT0= (rEXTINT0&0xffff00FF)|0x00000400; pISR_EINT2=(unsigned)Keyaddnumb; rINTMOD=0x0; //设置为IRQ模式rINTMSK&=~(BIT_EINT2); //打开keyboard中断//result(); */ //break; // } else{ allnumber[counter++]=key_number; } yes_key=0; } if(yes_key==0&&operation==0) { int j=0,p; if(edge<1&&counter>0) { //if(edge<1){ for(j=1;j<=counter;j++)write7279(DECODE1+5-j+1,allnumber[j-1]); }elseif(edge>1&&counter>0){send_byte(CMD_RESET);write7279(0x98,0xff);for(j=1;j<=counter-edge;j++)write7279(DECODE0+5+1-j,allnumber[edge+j-1]);}//else send_byte(CMD_RESET);}elseif(0<operation<5){edge=counter;operation=0;}}while(1);#include "2410addr.h"#include "7279.h"void Init7279(void){rGPEUP = rGPEUP|0x3800; //使用GPE11 GPE12 GPE13,去掉对应上拉功能rGPECON = (rGPECON&0xf03fffff)|0x05000000; // GPE11:In Data;GPE12:Out Data;GPE13:Out CLKrGPFUP = rGPFUP|0x0c;//使用GPF2 GPF3//rGPFCON = (rGPFCON&0xff0f)|0x0040; //GPF2:In Key;GPF3:Out 7279CS rGPFCON = (rGPFCON&0xff0f)|0x0060; //GPF2:In Key;GPF3:Out 7279CSrGPFDAT = rGPFDAT|0x08; //GPF3=1rGPFDAT = rGPFDAT&0xf7; //GPF3=0 选通7279rGPGUP = rGPGUP|0x0040; //使用GPG6,去掉对应上拉功能rGPGCON = (rGPGCON&0xffffcfff)|0x01000; //GPG6:Out 74H125 C1&(~C2) rGPGDAT = rGPGDAT&0xffbf; //GPG6=0}void write7279(unsigned char cmd ,unsigned char dta){send_byte(cmd);send_byte(dta);}unsigned char read7279(unsigned char command) {send_byte(command);return(receive_byte());}void send_byte(unsigned char out_byte) { unsigned char i;setcsLOW;long_delay();for(i=0;i<8;i++){if(out_byte&0x80){setdatHIGH;}else{setdatLOW;}setclkHIGH;short_delay();setclkLOW;short_delay();out_byte= out_byte*2;}setdatLOW;}unsigned char receive_byte(void){unsigned char i, in_byte;setdatZ;short_delay();for(i=0;i<8;i++){setclkHIGH;short_delay();in_byte=in_byte*2;if(dat){in_byte = in_byte|0x01; } setclkLOW;short_delay();}setdatL;return (in_byte);}void long_delay(void) {unsigned char i;for(i=0;i<0x30;i++);}void short_delay(void) {unsigned char i;for(i=0;i<0x0a;i++);}void delay10ms(unsigned char time) {unsigned char i;unsigned int j;for(i=0;i<time;i++){for(j=0;j<0x3300;j++){if(!key){//key_int();}}}}#ifndef __7279_H__#define __7279_H__void write7279(unsigned char,unsigned char); unsigned char read7279(unsigned char); void send_byte(unsigned char);unsigned char receive_byte(void);。
C#实现简易计算器功能(附源码)
C#实现简易计算器功能(附源码)本⽂实例为⼤家分享了C#实现简易计算器功能的具体代码,供⼤家参考,具体内容如下剖析:1、先设计界⾯(按钮、⽂本框(⼀个显⽰算式,⼀个显⽰结果))布局2、单击按钮将其对应内容显⽰在⽂本框中3、单击符号(+、-、×、÷、%)时将第⼀次输⼊的数储存起来4、单击等号时将第⼆次输⼊的数存储起来并将第⼀次输⼊的数与第⼆次输⼊的数按照所单击的符号进⾏运算将结果显⽰在第⼀个⽂本框中5、单击C时将两个⽂本框中的内容清空重点:1、声明⼀个bool类型的变量⽤于实现单击符号再次输⼊数字时第⼀次输⼊的数字清空显⽰第⼆次输⼊的数字2、声明两个double类型的变量⽤于装第⼀次输⼊的数和装第⼆次输⼊的数3、声明⼀个string类型的变量⽤于判断运算符号界⾯布局:具体代码如下:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace Test_Calculator{public partial class Form1 : Form{public Form1(){InitializeComponent();}//声明三个变量string type; //符号类型double x;//装第⼀个数(按符号(+-×÷%)时textbox1中的数字)double y;//装第⼆个数(按等号时textbox1中的数字)bool c=false;private void Form1_Load(object sender, EventArgs e){this.CenterToScreen();//窗体居中显⽰this.Text = "计算器";this.FormBorderStyle = FormBorderStyle.FixedToolWindow; textBox1.ReadOnly = true;//⽂本框只读textBox2.TabIndex = 0;//光标焦点在textbox2中}private void button1_Click(object sender, EventArgs e){if (c==true){c = false;textBox1.Text = "";}textBox1.Text += "1";textBox2.Text += "1";}private void button2_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "2";textBox2.Text += "2";}private void button3_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "3";textBox2.Text += "3";}private void button4_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "4";textBox2.Text += "4";}private void button5_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "5";textBox2.Text += "5";}private void button6_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "6";textBox2.Text += "6";}private void button7_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "7";textBox2.Text += "7";}private void button8_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "8";textBox2.Text += "8";}private void button9_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "9";textBox2.Text += "9";}private void button10_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "0";textBox2.Text += "0";}private void button11_Click(object sender, EventArgs e) {textBox1.Text += ".";textBox2.Text += ".";}private void button12_Click(object sender, EventArgs e) {textBox1.Text = "";textBox2.Text = "";}private void button13_Click(object sender, EventArgs e) {c = true;type = "+";textBox2.Text += "+";x = double.Parse(textBox1.Text);}private void button14_Click(object sender, EventArgs e){c = true;type = "-";textBox2.Text += "-";x = double.Parse(textBox1.Text);}private void button15_Click(object sender, EventArgs e){c = true;type = "×";textBox2.Text += "×";x = double.Parse(textBox1.Text);}private void button16_Click(object sender, EventArgs e){c = true;type = "÷";textBox2.Text += "÷";x = double.Parse(textBox1.Text);}private void button18_Click(object sender, EventArgs e){c = true;type = "%";textBox2.Text += "%";x = double.Parse(textBox1.Text);}private void button17_Click(object sender, EventArgs e){y = double.Parse(textBox1.Text);//法⼀while (type=="+"){textBox1.Text = (x + y).ToString();textBox2.Text += "=" + textBox1.Text;return;}while (type == "-"){textBox1.Text = (x - y).ToString();textBox2.Text += "=" + textBox1.Text;return;}while (type == "×"){textBox1.Text = (x * y).ToString();textBox2.Text += "=" + textBox1.Text;return;}while (type == "÷"){if (y!=0){textBox1.Text = (x / y).ToString();textBox2.Text += "=" + textBox1.Text;}else{MessageBox.Show("请重新输⼊","错误",MessageBoxButtons.OK,rmation); textBox1.Text = "";textBox2.Text = "";}return;}while (type == "%"){textBox1.Text = (x % y).ToString();textBox2.Text += "=" + textBox1.Text;return;}//法⼆://if (type=="+")//{// textBox1.Text=(x + y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="-")//{// textBox1.Text = (x - y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="×")//{// textBox1.Text = (x * y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="÷")//{// textBox1.Text = (x / y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="%")//{// textBox1.Text = (x % y).ToString();// textBox2.Text += "=" + textBox1.Text; //}}}}效果图:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
简易计算器源代码--java
package calculator;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.math.BigDecimal;import javax.swing.*;public class Operation extends JFrame implements ActionListener{/****/private static final long serialVersionUID = 1L;private final String str[] = {"7","8","9","/","4","5","6","*","1","2", "3","-",".","0","=","+"};private final JButton[] JB = new JButton[str.length];private final JButton reset = new JButton("CE");private final JTextField display = new JTextField("");Operation(){super("计算器");JPanel panel1 = new JPanel(new BorderLayout());JPanel panel2 = new JPanel(new GridLayout(4,4));panel1.add(BorderLayout.CENTER, display);panel1.add(BorderLayout.EAST, reset);int i;for( i = 0;i < str.length;i++){JB[i] = new JButton(str[i]);panel2.add(JB[i]);}getContentPane().setLayout(new BorderLayout());getContentPane().add(BorderLayout.NORTH,panel1);getContentPane().add(BorderLayout.SOUTH, panel2);setSize(800,800);for(i = 0;i < str.length;i++){JB[i].addActionListener(this);}reset.addActionListener(this);display.addActionListener(this);setVisible(true);setDefaultCloseOperation((WindowConstants.DISPOSE_ON_CLOSE));pack();}public void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根Object target = e.getSource();String label = e.getActionCommand();if(target == reset){handlereset();}else if("0123456789.".indexOf(label)>=0){handleNumber(label);}elsehandleOperator(label);}private void handleNumber(String key) {// TODO 自动生成的方法存根if ((isFirstDigit)&&("0123456789".indexOf(key)>=0))display.setText(key);else if ((key.equals(".")))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}boolean isFirstDigit = true;double number1 = 0.0;double number2 = 0.0;String operator = "=";BigDecimal df ;private void handlereset() {// TODO 自动生成的方法存根display.setText("");isFirstDigit = true;operator = "=";}public void handleOperator(String key) {if (operator.equals("+")){number1 = Double.valueOf(display.getText());number2 = add(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("-")){number1 = Double.valueOf(display.getText());number2 = sub(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("*")){number1 = Double.valueOf(display.getText());number2 = mul(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("/")){number1 = Double.valueOf(display.getText());if(number1 == 0)display.setText("error");else{number2 = div(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}}else if (operator.equals("=")){number2 = Double.valueOf(display.getText());display.setText(String.valueOf(number2));}operator = key;isFirstDigit = true;}private double div(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 / key2;return result;}private double mul(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 * key2;return result;}private double sub(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = key1 - key2;return result;}private double add(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = number1 + number2;return result;}public static void main(String[] args) {new Operation();}}。
编写一个简易计算器的源代码
AStack.h#ifndef ASTACK_HEADER#define ASTACK_HEADER#include <iostream>using namespace std;template <class Elem> class AStack{private:int size;int top;Elem* listArray;public:AStack(){ size = 100; top = 0; listArray = new Elem[100]; }~AStack(){ delete [] listArray; }void clear() { top = 0; }bool push(Elem& item){if (top == size) return false;else { listArray[top++] = item; return true; } }bool pop(Elem& it){if (top == 0) return false;else { it = listArray[--top]; return true; }}bool topValue(Elem& it) const{if (top == 0) return false;else { it = listArray[top - 1]; return true; } }int length() const { return top; }};#endifFunction.cpp#include "function.h"#include "AStack.h"#include <math.h>#include <stdio.h>void calUserInfo(){cout<<"\t* 智能计算器V1.0*"<<endl;cout<<"\t*********************"<<endl;cout<<"\t* 1 * 2 * 3 * + * - *"<<endl;cout<<"\t* 4 * 5 * 6 * * * / *"<<endl;cout<<"\t* 7 * 8 * 9 * 0 * % *"<<endl;cout<<"\t* & * ^ * = * ( * ) *"<<endl;cout<<"\t*********************"<<endl; }int isp(char& ch){switch(ch){case '=':return 0;break;case '+':case '-':return 3;break;case '*':case '/':case '%':return 5;case '(':return 1;break;case ')':return 8;break;case '^':case '&':return 7;break;}}int osp(char& ch) {switch(ch) {case '=':return 0;break;case '+':case '-':return 2;break;case '*':case '/':case '%':return 4;break;case '(':return 8;break;case ')':break;case '^':case '&':return 6;break;}}double extract(double x,double y){return pow(x,1/y);}bool cal(char op, double x, double y, double& r) {int o = 0;switch(op){case '-':r = x - y;break;case '+':r = x + y;break;case '/':r = x / y;break;case '%':(int) o = (int)x % (int)y;r = (double)o;break;case '*':r = x * y;case '&':r = extract(x,y);break;case '^':r = pow(x,y);break;}return true;}bool isDigit(char ch){if (((int)ch >= 48) && ((int)ch <= 57))return true;else return false;}bool isPoint(char ch){if (ch == '.')return true;else return false;}bool isOperator(char ch){if ((ch == '=') || (ch == '-') || (ch == '+') || (ch == '(') || (ch == ')') || (ch == '*') || (ch == '&') ||(ch == '/') ||(ch == '%') ||(ch == '^'))return true;else return false;}double turnDigit(char ch){double value;value = (double)ch - 48;return value;}double newDigit(double prior_digit, double now_digit, bool isHavePoint, double point_num){double value;if(!isHavePoint){value = prior_digit*10 + now_digit;}else{value = prior_digit + now_digit/(pow(10,point_num));}return value;}Function.h#ifndef FUNCTION_HEADER#define FUNCTION_HEADER//友好的用户界面void calUserInfo();//用于记录处于栈内的优先级int isp(char& ch);//用于记录栈外的优先级int osp(char& ch);//相当于value = x op y;如果cal成功,然后将value的值返回r,用r来保存bool cal(char op, double x, double y, double& r);//判断是否为字符bool isDigit(char ch);//判断是否为小数点bool isPoint(char ch);//判断是否为操作运算符bool isOperator(char ch);//将数字的字符状态转化成double状态double turnDigit(char ch);//如果几个数字或加一个小数点连在一起,这说明他们是同一个数字的不同位数,此函数将不同连在一起的数字//组成新的数字double newDigit(double prior_digit, double now_digit, bool isHavePoint, double point_num);#endifMain.cpp#include "AStack.h"#include "function.h"#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;int main(){char str[100] = "\0";AStack<double> opnd; //用于存放数据AStack<char> optr; //用于存放操作符char now_ch = '='; //用于记录当前字符char prior_ch = '\0'; //用于记录前一个字符double now_dig = 0; //用于记录当前一个数字double prior_dig = 0; //用于记录前一个数字double value = 0; //用于存放计算后的值bool point = false; //用于判断是否有小数点int point_num = 1; //用于记录数字后面的小数点位数char topValue; //用于记录opnd的top上的值char option = 'Y'; //用于判断是否要继续运算do{prior_dig = 0; //在opnd中提前放一个0now_ch = '=';opnd.push(prior_dig);optr.push(now_ch);system("cls");calUserInfo();cout << "请输入表达式(以等号结束):" << endl;cin >> str;bool exitPoint = false;/*对每个字符的处理*/for(int i = 0; i < strlen(str); i++){now_ch = str[i];/*判断是不是数字以及相关操作*/if (isDigit(now_ch)){now_dig = turnDigit(now_ch);if (isDigit(prior_ch)){opnd.pop(prior_dig);if(exitPoint){point = true;now_dig = newDigit(prior_dig, now_dig,point,point_num);point_num++;}elsenow_dig = newDigit(prior_dig, now_dig,point,point_num);}if(isPoint(prior_ch)){opnd.pop(prior_dig);now_dig = newDigit(prior_dig, now_dig,point,point_num);exitPoint = true;point_num++;}value = now_dig;opnd.push(now_dig);prior_ch = now_ch;}/*判断是不是小数点以及相关操作*/else if (isPoint(now_ch)){point = true;prior_ch = now_ch;}/*判断是不是操作符以及相关操作*/else if (isOperator(now_ch)){/*对用于数字操作的相关标记量进行清空,方便下一次数字操作*/point = false;point = 0;exitPoint = false;point_num = 1;/*看optr中是否有操作符存在,若不存在,则只放一个操作符进去*//* 但不进行任何操作*/if(optr.length() <= 1){optr.push(now_ch);prior_ch = now_ch;}/*optr已有操作符存在的话,开始进行优先级的比较*/else{optr.pop(topValue);/* 栈内优先级小于栈外优先级*/if(isp(topValue) < osp(now_ch)){optr.push(topValue);optr.push(now_ch);prior_ch = now_ch;}/*栈内优先级大于栈外优先级*/else if(isp(topValue) > osp(now_ch)){if(now_ch == ')' && topValue == '('){break;}do{double x = 1,y = 0;opnd.pop(x);opnd.pop(y);if( cal(topValue,y,x,value) ){opnd.push(value);}if(!optr.pop(topValue))break;}while(isp(topValue) > osp(now_ch));// if((topValue != '('))if (now_ch != ')'){optr.push(topValue);optr.push(now_ch);}prior_ch = now_ch;}/*其他情况报错*/elsebreak;}}/*其他情况报错*/elsecout << "输入的表达式错误,请检查!" << endl; }optr.pop(prior_ch);/*打印最后的计算值*/if(prior_ch == '='){cout << "最终得出的数据为: " << value << endl;}elsecout << "输入的表达式错误,请检查!" << endl;/*判断是否还要继续*/cout << "是否继续? ,继续'Y'/结束'N' :" << endl;cin >> option;/*清空数字栈和操作符栈*/opnd.clear();optr.clear();}while(option == 'Y');return 0;}。
简单的计算器源代码
//计算器,已经编译通过import java.awt.*;import java.awt.event.*;import javax.swing.*;public class testZ extends JFrame implements ActionListener{private JPanel jPanel1,jPanel2;private JTextField resultField;private JButton s1,s2,s3,s4,s5,s6,s7,s8,s9,s0,b1,b2,b3,b4,f1,f2; private boolean end,add,sub,mul,div;private String str;private double num1,num2;public testZ(){super("计算器");setSize(300,240);Container con=getContentPane();con.setLayout(new BorderLayout());jPanel1=new JPanel();jPanel1.setLayout(new GridLayout(1,1));jPanel2=new JPanel();jPanel2.setLayout(new GridLayout(4,4));resultField=new JTextField("0");jPanel1.add(resultField);con.add(jPanel1,BorderLayout.NORTH);s1=new JButton(" 1 "); s1.addActionListener(this);s2=new JButton(" 2 "); s2.addActionListener(this);s3=new JButton(" 3 "); s3.addActionListener(this);s4=new JButton(" 4 "); s4.addActionListener(this);s5=new JButton(" 5 "); s5.addActionListener(this);s6=new JButton(" 6 "); s6.addActionListener(this);s7=new JButton(" 7 "); s7.addActionListener(this);s8=new JButton(" 8 "); s8.addActionListener(this);s9=new JButton(" 9 "); s9.addActionListener(this);s0=new JButton(" 0 "); s0.addActionListener(this);b1=new JButton(" + "); b1.addActionListener(this);b2=new JButton(" - "); b2.addActionListener(this);b3=new JButton(" * "); b3.addActionListener(this);b4=new JButton(" / "); b4.addActionListener(this);f1=new JButton(" . "); f1.addActionListener(this);f2=new JButton(" = "); f2.addActionListener(this);jPanel2.add(s1);jPanel2.add(s2);jPanel2.add(s3);jPanel2.add(b1);jPanel2.add(s4);jPanel2.add(s5);jPanel2.add(s6);jPanel2.add(b2);jPanel2.add(s7);jPanel2.add(s8);jPanel2.add(s9);jPanel2.add(b3);jPanel2.add(s0);jPanel2.add(f1);jPanel2.add(f2);jPanel2.add(b4);con.add(jPanel2,BorderLayout.CENTER);}public void num(int i){String s = null;s=String.valueOf(i);if(end){//如果数字输入结束,则将文本框置零,重新输入resultField.setText("0");end=false;}if((resultField.getText()).equals("0")){//如果文本框的内容为零,则覆盖文本框的内容resultField.setText(s);}else{//如果文本框的内容不为零,则在内容后面添加数字str = resultField.getText() + s;resultField.setText(str);}}public void actionPerformed(ActionEvent e){ //数字事件 if(e.getSource()==s1)num(1);else if(e.getSource()==s2)num(2);else if(e.getSource()==s3)num(3);else if(e.getSource()==s4)num(4);else if(e.getSource()==s5)num(5);else if(e.getSource()==s6)num(6);else if(e.getSource()==s7)num(7);else if(e.getSource()==s8)num(8);else if(e.getSource()==s9)num(9);else if(e.getSource()==s0)num(0);//符号事件else if(e.getSource()==b1)sign(1);else if(e.getSource()==b2)sign(2);else if(e.getSource()==b3)sign(3);else if(e.getSource()==b4)sign(4);//等号else if(e.getSource()==f1){str=resultField.getText();if(str.indexOf(".")<=1){str+=".";resultField.setText(str);}}else if(e.getSource()==f2){num2=Double.parseDouble(resultField.getText());if(add){num1=num1 + num2;}else if(sub){num1=num1 - num2;}else if(mul){num1=num1 * num2;}else if(div){num1=num1 / num2;}resultField.setText(String.valueOf(num1));end=true;}}public void sign(int s){if(s==1){add=true;sub=false;mul=false;div=false;}else if(s==2){add=false;sub=true;mul=false;div=false;}else if(s==3){add=false;sub=false;mul=true;div=false;}else if(s==4){add=false;sub=false;mul=false;div=true;}num1=Double.parseDouble(resultField.getText()); end=true;}public static void main(String[] args){testZ th1=new testZ();th1.show();}}。
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>///必需的设计器变量。
计算器源代码
这几天在做一个小计算器,经过两天的调试终于算是做完了(可能还有小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编写简易计算器附源代码超详细
超详细因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用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>/// 必需的设计器变量。
简易计算器源码
#include<iostream>using namespace std;/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char** argv) {float x; /*定义一个x*/float y; /*定义一个y*/cin >> x; /*输入x */cin >> y; /*输入y */cout << "计算结果(加法):" << x+y << endl << "计算结果(减法):" << x-y << endl << "计算结果(乘法):" << x*y << endl <<"计算结果(除法):" << x/y << endl <<"BY:QHN~~~"; /*计算过程*/return 0;}这是我自己与2016年9月27日星期二编写的简易计算器源码,仅供参考。
———————————————————————————————————————————————————#include<iostream>using namespace std;/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char** argv) {float x; /*定义一个x*/float y; /*定义一个y*/cin >> x; /*输入x */cin >> y; /*输入y */cout << "计算结果(加法):" << x+y << endl << "计算结果(减法):" << x-y << endl << "计算结果(乘法):" << x*y << endl <<"计算结果(除法):" << x/y << endl <<"BY:QHN~~~"; /*计算过程*/return 0;}这是我自己与2016年9月27日星期二编写的简易计算器源码,仅供参考。