计算器设计代码

合集下载

计算器Java编程完全代码

计算器Java编程完全代码

计算器Java编程代码1、界面截图1、程序代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Counter implements ActionListener {// 改进小数问题private boolean append = false;JButton[] jb = new JButton[20];JTextField jtf = new JTextField(19);String[] st = { "Backs", "CE", "C", "+", " 7 ", " 8 ", " 9", "-"," 4 ", " 5 ", " 6", "*", " 1 ", " 2 ", " 3", "/"," . ", "+/-", " 0", "=", };String num1 = "0";String operator = "+";public Counter() {JFrame jf = new JFrame("计算器");// 界面设置GridLayout gl = new GridLayout(6, 1);jf.setLayout(gl);JPanel jp0 = new JPanel();jp0.add(jtf);jf.add(jp0);JPanel jp1 = new JPanel();for (int i = 0; i < 4; i++) {jb[i] = new JButton(st[i]);jp1.add(jb[i]);}jf.add(jp1);JPanel jp2 = new JPanel();for (int i = 4; i < 8; i++) {jb[i] = new JButton(st[i]);jp2.add(jb[i]);}jf.add(jp2);JPanel jp3 = new JPanel();for (int i = 8; i < 12; i++) {jb[i] = new JButton(st[i]);jp3.add(jb[i]);}jf.add(jp3);JPanel jp4 = new JPanel();for (int i = 12; i < 16; i++) { jb[i] = new JButton(st[i]);jp4.add(jb[i]);}jf.add(jp4);JPanel jp5 = new JPanel();for (int i = 16; i < 20; i++) { jb[i] = new JButton(st[i]);jp5.add(jb[i]);}jf.add(jp5);jtf.setEditable(false);// 文本框不可编辑jf.setResizable(false);// 窗口不可编辑jf.pack();// 自动调整窗口的大小// jf.setSize(240, 220);jf.setLocation(450, 300);jf.setVisible(true);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);for (int i = 0; i < 20; i++) {// 注册监听jb[i].addActionListener(this);}}public void actionPerformed(ActionEvent ae) {String s = ae.getActionCommand();if (s.trim().matches("^\\d$")) {// 判断是输入的是否是数字if (append) {// 追加数字String ss = jtf.getText().trim();jtf.setText(ss + s.trim());} else {// 替换文本框原来的数字jtf.setText(s.trim());append = true;}} else if ("+-/*".indexOf(s.trim()) != -1) {// 判断按的是否是四则运算符num1 = jtf.getText();// 将第一次输入的数存储起来operator = s.trim();// 将输入的符号存储起来append = false;} else if ("=".equals(s.trim())) {String num2 = jtf.getText();double d1 = Double.parseDouble(num1);double d2 = Double.parseDouble(num2);if ("+".equals(operator)) {// 加法运算d1 = d1 + d2;} else if ("-".equals(operator)) {// 减法运算d1 = d1 - d2;} else if ("*".equals(operator)) {// 乘法运算d1 = d1 * d2;} else if ("/".equals(operator)) {// 除法运算d1 = d1 / d2;}jtf.setText(d1 + "");// 显示结果append = false;} else if (".".equals(s.trim())) {// 判断小数点String temp = jtf.getText();if (temp.indexOf(".") == -1) {jtf.setText(temp + ".");append = true;}} else if ("+/-".equals(s.trim())) {// 判断+/-String temp = jtf.getText();if(temp.startsWith("-")) {// 如果该数是负数则取负号后的数字jtf.setText(temp.substring(1));} else {// 如果是正数则在这个数前加上负号jtf.setText("-" + temp);}} else if ("CE".equals(s.trim()) || "C".equals(s.trim())) {// 判断复位键jtf.setText("0");append = false;} else if ("BackS".equals(s.trim())) {// 判断BackS键(删除)String temp = jtf.getText();if (temp.length() > 0) {jtf.setText(temp.substring(0, temp.length() - 1));}}}public static void main(String[] args) {new Counter();}}。

简易计算器程序源代码

简易计算器程序源代码

简易计算器程序源代码下面是一个简易计算器程序的源代码,它可以执行基本的四则运算:```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("请输入有效的选择")```运行这个程序,你将看到一个简易的计算器菜单。

用java代码写的简易计算器(可以实现基本的加减乘除功能)

用java代码写的简易计算器(可以实现基本的加减乘除功能)

⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。

计算器源代码

计算器源代码

#include<stdio.h>#include<iostream.h>#include<stdlib.h>#include<string.h>#include<ctype.h>typedef float DataType;typedef struct{DataType *data;int max;int top;}Stack;void SetStack(Stack *S,int n){S->data=(DataType*)malloc(n*sizeof(DataType)); if(S->data==NULL){printf("overflow");exit(1);}S->max=n;S->top=-1;}void FreeStack(Stack *S){free(S->data);}int StackEmpty(Stack *S){if(S->top==-1)return(1);return(0);}DataType Peek(Stack *S){if(S->top==S->max-1){printf("Stack is empty!\n");exit(1);}return(S->data[S->top]);}void Push(Stack *S,DataType item){if(S->top==S->max-1){printf("Stack is full!\n");exit(1);}S->top++;S->data[S->top]=item;}DataType Pop(Stack *S){if(S->top==-1){printf("Pop an empty stack!\n");exit(1);}S->top--;return(S->data[S->top+1]);}typedef struct{char op;int inputprecedence;int stackprecedence;}DataType1;typedef struct{DataType1 *data;int max;int top;}Stack1;void SetStack1(Stack1 *S,int n){S->data=(DataType1*)malloc(n*sizeof(DataType1)); if(S->data==NULL){printf("overflow");exit(1);}S->max=n;S->top=-1;}void FreeStack1(Stack1 *S){free(S->data);}int StackEmpty1(Stack1 *S){if(S->top==-1)return(1);return(0);}DataType1 Peek1(Stack1 *S){if(S->top==S->max-1){printf("Stack1 is empty!\n");exit(1);}return(S->data[S->top]);}void Push1(Stack1 *S,DataType1 item) {if(S->top==S->max-1){printf("Stack is full!\n");exit(1);}S->top++;S->data[S->top]=item;}DataType1 Pop1(Stack1 *S){if(S->top==-1){printf("Pop an empty stack!\n");exit(1);}S->top--;return(S->data[S->top+1]);}DataType1 MathOptr(char ch){DataType1 optr;optr.op=ch;switch(optr.op){case'+':case'-':optr.inputprecedence=1;optr.stackprecedence=1;break;case'*':case'/':optr.inputprecedence=2;optr.stackprecedence=2;break;case'(':optr.inputprecedence=3;optr.stackprecedence=-1;break;case')':optr.inputprecedence=0;optr.stackprecedence=0;break;}return(optr);}void Evaluate(Stack *OpndStack,DataType1 optr) {DataType opnd1,opnd2;opnd1=Pop(OpndStack);opnd2=Pop(OpndStack);switch(optr.op){case'+':Push(OpndStack,opnd2+opnd1);break;case'-':Push(OpndStack,opnd2-opnd1);break;case'*':Push(OpndStack,opnd2*opnd1);break;case'/':Push(OpndStack,opnd2/opnd1);break;}}int isoptr(char ch){if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='(')return(1);return(0);}void Infix(char *str){int i,k,n=strlen(str);char ch,numstr[10];DataType opnd;DataType1 optr;Stack OpndStack;Stack1 OptrStack;SetStack(&OpndStack,n);SetStack1(&OptrStack,n);k=0;ch=str[k];while(ch!='=')if(isdigit(ch)||ch=='.'){for(i=0;isdigit(ch)||ch=='.';i++){numstr[i]=ch;k++;ch=str[k];}numstr[i]='\0';opnd= atof(numstr);Push(&OpndStack,opnd);}elseif(isoptr(ch)){optr=MathOptr(ch);while(Peek1(&OptrStack).stackprecedence>=optr.inputprecedence) Evaluate(&OpndStack,Pop1(&OptrStack));Push1(&OptrStack,optr);k++;ch=str[k];}else if(ch==')'){optr=MathOptr(ch);while(Peek1(&OptrStack).stackprecedence>=optr.inputprecedence) Evaluate(&OpndStack,Pop1(&OptrStack));Pop1(&OptrStack);k++;ch=str[k];}while(!StackEmpty1(&OptrStack))Evaluate(&OpndStack,Pop1(&OptrStack));opnd=Pop(&OpndStack);cout<<"你输入表达式的计算结果为"<<endl;printf("%-6.2f\n",opnd);FreeStack(&OpndStack);FreeStack1(&OptrStack);}void main(){cout<<"请输入你要计算的表达式,并以“=”号结束。

易语言计算器设计演示代码

易语言计算器设计演示代码

说明(数值1。

数值2。

请输入需要计算的数值都是标签。

计算结果显示在“请输入需要计算的数值”那个位置。

输入计算数值的位置是两个编辑框。

其他六个是按钮,先把图形界面做好,名字按下面程序中给定的命名,代码完全复制过去,那么就能够用了)
.版本2
.程序集窗口程序集1
.子程序_结果标签_反馈事件, 整数型
.参数参数一, 整数型
.参数参数二, 整数型
.子程序_相加_被单击
结果标签.标题=“相加结果:”+到文本(到数值(数值1编辑框.内容) +到数值(数值2编辑框.内容))
.子程序_按钮2_被单击
结果标签.标题=“相减结果:”+到文本(到数值(数值1编辑框.内容) -到数值(数值2编辑框.内容))
.子程序_相乘_被单击
结果标签.标题=“相乘结果:”+到文本(到数值(数值1编辑框.内容) ×到数值(数值2编辑框.内容))
.子程序_相除_被单击
.如果(到数值(数值2编辑框.内容) =0)
信息框(“除数不能为0”, #错误图标, “错误!”)
.否则
.如果结束
结果标签.标题=“相除结果:”+到文本(到数值(数值1编辑框.内容) ÷到数值(数值2编辑框.内容))
.子程序_清零_被单击
数值1编辑框.内容=“”
数值2编辑框.内容=“”
结果标签.标题=“请输入需要计算的数值”
.子程序_退出_被单击
.局部变量返回值, 整数型
.局部变量如果真, 整数型
返回值=信息框(“确定要退出程序吗?”, #是否钮+#信息图标, )
.如果真(返回值=#是钮)
结束()
.如果真结束。

简易计算器代码

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

用c语言编写的计算器源代码

用c语言编写的计算器源代码

作品:科学计算器作者:欧宗龙编写环境:vc++6.0语言:c#include"stdafx.h"#include<stdio.h>#include<windows.h>#include<windowsx.h>#include"resource.h"#include"MainDlg.h"#include<math.h>#include<string.h>#definePI3.141593BOOLA_Op=FALSE;BOOLWINAPIMain_Proc(HWNDhWnd,UINTuMsg,WPARAMwParam,LPARAMlParam) {switch(uMsg){HANDLE_MSG(hWnd,WM_INITDIALOG,Main_OnInitDialog);HANDLE_MSG(hWnd,WM_COMMAND,Main_OnCommand);HANDLE_MSG(hWnd,WM_CLOSE,Main_OnClose);}returnFALSE;}BOOLMain_OnInitDialog(HWNDhwnd,HWNDhwndFocus,LPARAMlParam){returnTRUE;}voidTrimNumber(chara[])//判断并删除小数点后无用的零{for(unsignedi=0;i<strlen(a);i++){if(a[i]=='.'){for(unsignedj=strlen(a)-1;j>=i;j--){if(a[j]=='0'){a[j]='\0';}elseif(a[j]=='.'){a[j]='\0';}elsebreak;}}}}doubleOperate(charOperator,doublen1,doublen2)//判断符号,进行相应的运算{if(Operator=='0'){}if(Operator=='+'){n2+=n1;}if(Operator=='-'){n2=n1-n2;}if(Operator=='*'){n2*=n1;}if(Operator=='/'){n2=n1/n2;}if(Operator=='^'){n2=pow(n1,n2);}return n2;}////////////////////////////////////////////////voidIntBinary(chara[],intn){if(n>1)IntBinary(a,n/2);sprintf(a,"%s%i",a,n%2);}voiddecimal(chara[],doublem){if(m>0.000001){m=m*2;sprintf(a,"%s%d",a,(long)m);decimal(a,m-(long)m);}}voidBinary(chara[],doubleNum){charDecP[256]="";doublex,y;double*iptr=&y;x=modf(Num,iptr);decimal(DecP,x);IntBinary(a,(int)y);strcat(a,".");strcat(a,DecP);}////////////////////////////////////voidMain_OnCommand(HWNDhwnd,intid,HWNDhwndCtl,UINTcodeNotify) {staticDELTIMES=0;staticcharstr[256];staticcharOperator='0';staticdoubleRNum[3];switch(id){caseIDC_BUTTONN1://数字1{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"1");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN2://数字2{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"2");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN3://数字3{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"3");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN4://数字4{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"4");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN5://数字5{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"5");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN6://数字6{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"6");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN7://数字7{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"7");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN8://数字8{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"8");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN9://数字9{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"9");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;caseIDC_BUTTONN0://数字0{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"0");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));if(DELTIMES==0){strcat(str,".");}DELTIMES++;SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=FALSE;}break;caseIDC_BUTTONADD://加法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='+';DELTIMES=0;A_Op=TRUE;}break;caseIDC_BUTTONSUB://减法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);DELTIMES=0;A_Op=TRUE;Operator='-';}break;caseIDC_BUTTONMUL://乘法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='*';DELTIMES=0;A_Op=TRUE;}break;caseIDC_BUTTONDIV://除法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='/';DELTIMES=0;A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='^';DELTIMES=0;}break;caseIDC_BUTTONPI://圆周率PI,弧度{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));if(atof(str)!=0){RNum[2]=atof(str)*PI;sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);}else{sprintf(str,"%f",PI);SetDlgItemText(hwnd,IDC_EDIT,str);}A_Op=TRUE;}break;caseIDC_BUTTONSQRT://开根号{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=sqrt(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONSIN://三角函数sin函数{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=sin(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=cos(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=tan(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONSQ://平方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str)*atof(str);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str)*atof(str)*atof(str);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=exp(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=pow(10,atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONLN://lnx{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=log(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONLOG10://log10{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=log10(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;caseIDC_BUTTONBINARY://十进制转换为二进制{chara[256]="";GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str);Binary(a,RNum[2]);strcpy(str,a);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case{DELTIMES=0;Operator='0';RNum[0]=RNum[1]=RNum[2]=0;memset(str,0,sizeof(str));SetDlgItemText(hwnd,IDC_EDIT,NULL);A_Op=FALSE;}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));inti=strlen(str);str[i-1]='\0';SetDlgItemText(hwnd,IDC_EDIT,str);}break;case{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='0';DELTIMES=0;}break;default:break;}}voidMain_OnClose(HWNDhwnd){EndDialog(hwnd,0);}本人拙作,如有不足之处请谅解。

计算器程序代码

计算器程序代码

计算器的程序,很简单,只弄了+-法,乘除没弄,只要把代码看懂照着+-法改一下就行了,不过涉及到多级运算只用一个LastClick是不行的程序的控件就两种CommandBotton和TextBox都是最基本的先创建十一个CommandBotton,Caption改为0-9以及一个"."(小数点)创建三个CommandBotton,Caption改为“-”,“+”“=”创建五个CommandBotton,Caption改为“CM”(clearmemory) “MR”(memoryrecall) “MS”(memorysave) “C”(clear) “AC”(allclear)再创建个TextBox下面的是对应代码,很清楚Dim Counter As Double ‘这个用来记录结果Dim Memory As Double ‘用来记录你保存的数,这个我们用的科学计算器里也有Dim Reg As Double ‘这个也是用来记录结果Dim CalcNumber As Long ‘这个是判断:1当之前点过一次+或-时再点一次运算结果,2如果前面没点过+或-则不进行运算Dim DisplayFromNew As Boolean ‘这个用来判断输入框状态:是接着输入还是从新输入新的数Dim AlreadyDecimalThere As Boolean ‘这个用来判断是否能用小数点Dim LastClick As String ‘这个用来记录最后一次选择的运算法则Private Sub Form_Load()Display.Text = "0"Reg = 0CalcNumber = 0DisplayFromNew = TrueAlreadyDecimalThere = FalseEnd SubPrivate Sub AllClear_Click() ‘这个不用说了,是全部清空DisplayFromNew = True ‘恢复到初始状态Counter = 0Display.Text = "0" ‘清空输入框CalcNumber = 0Reg = 0AlreadyDecimalThere = False ‘恢复到初始状态End SubPrivate Sub Clear_Click() ‘清空,但不清空纪录DisplayFromNew = TrueDisplay.Text = "0"End SubPrivate Sub ClearMemory_Click() ‘清空纪录Memory = 0End SubPrivate Sub Decimal_Click() ‘关于小数点的If AlreadyDecimalThere = False ThenAddDisplayDigit "."AlreadyDecimalThere = True ‘每次输入只能输一次小数点End IfEnd SubPrivate Sub Equals_Click() ‘等号时的If LastClick = "Minus" ThenIf CalcNumber = 0 ThenReg = CDbl(Display.Text) ‘记录DisplayFromNew = TrueCalcNumber = 1Else ‘这个的意思是,如果只点了法则(+或-)之后没点数,就加上前面输的数,但我觉得这样就等于前面输得数的2倍(+时)或0(-时),所以不用这么麻烦Counter = Reg - CDbl(Display.Text)Display.Text = CStr(Counter)DisplayFromNew = TrueAlreadyDecimalThere = FalseReg = CDbl(Display.Text)End IfElseIf LastClick = "Addition" Then ‘这是加法,和减法一样If CalcNumber = 0 ThenReg = CDbl(Display.Text)DisplayFromNew = TrueCalcNumber = 1ElseCounter = Reg + CDbl(Display.Text)Display.Text = CStr(Counter)DisplayFromNew = TrueAlreadyDecimalThere = FalseReg = CDbl(Display.Text)End IfEnd IfCalcNumber = 0End SubSub AddDisplayDigit(Additio n As String) ‘这一段十分重要,也是大家要学习的,就是自己创建一个函数,这样应用起来会十分方便If DisplayFromNew = True ThenDisplay.Text = Addition ‘当DisplayFromNew = True时(大家注意杂那几种情况下= True)输入栏从新显示刚输入的数DisplayFromNew = False ‘之后立即变为False,因为要接着这个数继续输入ElseDisplay.Text = Display.Text & Add ition ‘当DisplayFromNew = False 就是接着输入栏里已有的数字继续输入End IfEnd Sub注:为何要弄两种情况呢,因为当点击-或+时,要求输入栏从新记录Private Sub MemorySave_Click() ‘这是保存记录If DisplayFromNew = False ThenMemory = CDbl(Display.Text)End IfEnd SubPrivate Sub MemoryRecall_Click() ‘打开纪录Display = CStr(Memory)End SubPrivate Sub Minus_Click() ‘点击If CalcNumber = 0 ThenReg = CDbl(Display.Text)DisplayFromNew = TrueCalcNumber = 1Else ‘这个就是如果前面输过一次-号,再点-号就运算结果,这一点是很重要的,如果不加这个就无法进行连续运算Counter = Reg - CDbl(Display.Text)Display.Text = CStr(Counter)DisplayFromNew = TrueAlreadyDecimalThere = FalseReg = CDbl(Display.Text)End IfLastClick = "Minus"End SubPrivate Sub Plus_Click() ‘和减法一样If CalcNumber = 0 ThenReg = CDbl(Display.Text)DisplayFromNew = TrueCalcNumber = 1ElseCounter = Reg + CDbl(Display.Text)Display.Text = CStr(Counter)DisplayFromNew = TrueAlreadyDecimalThere = FalseReg = CDbl(Display.Text)End IfLastClick = "Addition"End Sub‘下面的就简单了0-9,不过用到了前面定义的函数AddDisplayDigit,大家看到这个自定义函数的作用了吧Private Sub Nine_Click()AddDisplayDigit "9"End SubPrivate Sub Eight_Click()AddDisplayDigit "8"End SubPrivate Sub Seven_Click()AddDisplayDigit "7"End SubPrivate Sub Six_Click()AddDisplayDigit "6"End SubPrivate Sub Five_Click()AddDisplayDigit "5"End SubPrivate Sub Four_Click() AddDisplayDigit "4"End SubPrivate Sub Three_Click() AddDisplayDigit "3"End SubPrivate Sub Two_Click() AddDisplayDigit "2"End SubPrivate Sub One_Click() AddDisplayDigit "1"End SubPrivate Sub Zero_Click() AddDisplayDigit "0"End Sub。

C语言计算器代码

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

JAVA计算器源代码

JAVA计算器源代码

计算器源代码一、计算器源代码文件名:computer1.javaimport java.awt.*;import java.awt.event.*;public class computer1 extends Frame implements ActionListener{//声明窗口类并实现动作事件接口。

Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9;//声明数字按钮Button op,os,om,od,oe,oc;//声明操作按钮TextField tfd;//声明文本框String flg,rslt;//声明标志串、结果串Panel p1,p2,p3;//声明面板int i1,i2;float flt;computer1(){super("加减乘除计算器");n0 = new Button("0");//实现各按钮n1 = new Button("1");n2 = new Button("2");n3 = new Button("3");n4 = new Button("4");n5 = new Button("5");n6 = new Button("6");n7 = new Button("7");n8 = new Button("8");n9 = new Button("9");op = new Button("加");os = new Button("减");om = new Button("乘");od = new Button("除");oe = new Button("=");oc = new Button("c");tfd = new TextField(20);//实现文本框p1=new Panel();//实现各面板p2=new Panel();p3=new Panel();setLayout(new FlowLayout());//布局设计,用于安排按钮位置p1.add(n0);//将各数字按钮放入p1中p1.add(n1);p1.add(n2);p1.add(n3);p1.add(n4);p1.add(n5);p1.add(n6);p1.add(n7);p1.add(n8);p1.add(n9);p2.add(op);//将各操作按钮放入p2、p3中p2.add(os);p2.add(om);p2.add(od);p3.add(oe);p3.add(oc);setLayout(new BorderLayout());//布局设计,用于安排面板位置add("North",tfd);add("West",p1);add("Center",p2);add("East",p3);n0.addActionListener(this);//注册监听器到各按钮n1.addActionListener(this);n2.addActionListener(this);n3.addActionListener(this);n4.addActionListener(this);n5.addActionListener(this);n6.addActionListener(this);n7.addActionListener(this);n8.addActionListener(this);n9.addActionListener(this);op.addActionListener(this);os.addActionListener(this);om.addActionListener(this);od.addActionListener(this);oe.addActionListener(this);oc.addActionListener(this);addWindowListener(new closeWin());setSize(600,100);//确定窗口的尺寸setVisible(true);}public static void main (String args[]){new computer1();}public void actionPerformed(ActionEvent e){//处理鼠标事件的方法try{//异常处理if(e.getSource()==n0)//按数字键时tfd.setText(tfd.getText()+"0");if(e.getSource()==n1)tfd.setText(tfd.getText()+"1");if(e.getSource()==n2)tfd.setText(tfd.getText()+"2");if(e.getSource()==n3)tfd.setText(tfd.getText()+"3");if(e.getSource()==n4)tfd.setText(tfd.getText()+"4");if(e.getSource()==n5)tfd.setText(tfd.getText()+"5");if(e.getSource()==n6)tfd.setText(tfd.getText()+"6");if(e.getSource()==n7)tfd.setText(tfd.getText()+"7");if(e.getSource()==n8)tfd.setText(tfd.getText()+"8");if(e.getSource()==n9)tfd.setText(tfd.getText()+"9");if(e.getSource()==op){//按加号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "op";}if(e.getSource()==os){//按减号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "os";}if(e.getSource()==om){//按乘号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "om";}if(e.getSource()==od){//按除号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "od";}if(e.getSource()==oe){//按等号键时i2 = Integer.parseInt(tfd.getText());if(flg=="op"){rslt=Integer.toString(i1+i2);}if(flg=="os"){rslt=Integer.toString(i1-i2);}if(flg=="om"){rslt=Integer.toString(i1*i2);}if(flg=="od"){//除法需做小数处理flt=((float)i1)/((float)i2);rslt=Float.toString(flt);}tfd.setText(rslt);}if(e.getSource()==oc){//按清除键时tfd.setText("");flg = "";}}catch(Exception ex){}//扑捉到异常,但不进行处理}}class closeWin extends WindowAdapter{ //关闭窗口public void windowClosing(WindowEvent e){Frame frm=(Frame)(e.getSource());frm.dispose();System.exit(0);}}二、计算器界面三、修改后计算器界面。

自己写的计算器(加减乘除)代码

自己写的计算器(加减乘除)代码

⾃⼰写的计算器(加减乘除)代码⾸先是Calculator计算器类package zydCalr;public class Calculator {public double addition(double number1, double number2) {return number1+number2;}public double subtraction(double number1, double number2) {return number1-number2;}public double multiplication(double number1, double number2) {return number1*number2;}public double divsition(double number1, double number2) {return number1/number2;}}接下来是Execute运⾏类package zydCalr;import java.util.Scanner;public class Execution {public double execute(String str){String expression = str + "+1";// 初始化开始//char[] Cexpression = expression.toCharArray();// 创建运算器Calculator calculator = new Calculator();// 数值列表double[] numbers = new double[30];int numbersindex = 0;// 转型列表char[] sub = new char[30];// 数值下标位置int count = 0;// 符号列表char[] symbols = new char[10];int symbolsindex = 0;// temp1是数值列表上⼀个数值,temp2是当前的数值double temp1 = 0, temp2 = 0;;// 符号char symbol = 0;int flag = 1;// 初始化结束// 第⼀次遍历for (int i = 0; i < expression.length(); i++) {if (Cexpression[i] >= '0' && sub[i] <= '9') {sub[count++] = Cexpression[i];} else {// 字符串转型doubletemp2 = transition(sub,count);// 当flag=2时进⾏运算if (flag == 2) {flag = 1;// 获取数值列表前⼀个数值;temp1 = numbers[numbersindex - 1];// 判断symbol乘法还是除法,成功是乘法,失败为除法if (decide(symbol)==1) {temp2 = calculator.multiplication(temp1, temp2);} else {temp2 = calculator.divsition(temp1, temp2);}// 覆盖前⼀个数值numbersindex--;}// temp2存⼊数值列表numbers[numbersindex++] = temp2;// 获取符号symbol = Cexpression[i];// 转型数值下标位置清零count = 0;// 判断是否⼤于flag,flag=2,不⼤于则加⼊到符号列表if (judge(symbol) > flag) {flag = 2;} else {// 加⼊到符号列表symbols[symbolsindex++] = symbol;}}}double temp = numbers[0];count = 0;for (int i = 1; i < numbers.length; i++) {if (symbols[count] == '+') {temp += numbers[i];count++;} else if (symbols[count] == '-') {temp -= numbers[i];count++;}}return temp;}private static int judge(char symbol) {if (symbol == '+') {return 1;} else if (symbol == '-') {return 1;} else if (symbol == '*') {return 2;} else if (symbol == '/') {return 2;}return 0;}private static int decide(char symbol) {if (symbol == '*') {return 1;} else if (symbol == '/') {return 2;}return 2;}private static int transition(char[] sub1,int count) {int temp = 0;for (int i = 0; i < count; i++) {if (sub1[i] >= '0' && sub1[i] <= '9') {temp = temp * 10;temp += (sub1[i] - '0');}}return temp;}}产⽣表达式类package zydCalr;import java.util.Random;public class ProductionExpression {//⽣成数值public static String producerNumber() {int number = (int) (Math.random() * 50);return String.valueOf(number);}//⽣成数值public static String producerOpreator() {int number = (int) (Math.random() * 4);String[] operator = { "+", "-", "*", "/" };return operator[number];}//产⽣public static String producer(int i) {StringBuilder sb = new StringBuilder();int flag = (int) (Math.random() * 5);if(flag==1){sb.append("-");}sb.append(producerNumber());while (i > 0) {sb.append(producerOpreator());sb.append(producerNumber());i--;}return sb.toString();}//产⽣表达式public static String producerExpression() {int lenght = (int) (Math.random() * 5);if (lenght % 2 == 0) {lenght++;}String expression = producer(lenght);return expression;}}⽣产者类package zydCalr;import java.util.ArrayList;import java.util.List;public class Producer implements Runnable {static final int MAXQUEUE = 5;private List<String> messages = new ArrayList<String>(); private ProductionExpression pe=new ProductionExpression(); @Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {putMessage();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}private synchronized void putMessage() {while (messages.size() >= MAXQUEUE) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}//⽣成表达式messages.add(pe.producerExpression());notify();}public synchronized String getMessage() {while (messages.size() == 0) {try {notify();wait();} catch (InterruptedException e) {e.printStackTrace();}}String message = (String) messages.remove(0);notify();return message;}}消费者类package zydCalr;public class Consumer implements Runnable {Producer producer;Consumer(Producer producer) {this.producer = producer;}public void run() {while (true) {System.out.println("-------------开始⼀组表达式处理-------------");String message = producer.getMessage();System.out.println("⽣成表达式:" + message);Execution exe=new Execution();System.out.printf("处理结果:"+"%.2f\n",exe.execute(message));try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {Producer producer = new Producer();new Thread(producer).start();Consumer consumer = new Consumer(producer);new Thread(consumer).start();}}代码还是很简单的,主要有两个列表,⼀个列表存数值,⼀个列表存符号,如果符号是乘法或者除法,则把当前的数值和数值列表最后的数值相乘或相除,然后覆盖到数字列表的最后,如果不是,则存⼊数值列表的最后,符号列表添加当前的减法或者乘法,最后我发现许多细节的东西没有处理。

科学计算器源代码

科学计算器源代码

科学计算器源代码以下是一个简单的科学计算器的源代码,包含了基本的数学运算、三角函数、指数和对数运算、阶乘和组合运算等功能。

```#include <iostream>#include <cmath>using namespace std;//计算器类class ScientificCalculatorpublic://基本运算double add(double a, double b)return a + b;}double subtract(double a, double b)return a - b;}double multiply(double a, double b)return a * b;}double divide(double a, double b)if (b != 0)return a / b;} elsecout << "Error: Division by zero!" << endl; return 0;}}//三角函数运算double sine(double angle)return sin(angle);}double cosine(double angle)return cos(angle);}double tangent(double angle)return tan(angle);}//指数和对数运算double exponent(double x) return exp(x);}double logarithm(double x) return log10(x);}//阶乘运算double factorial(int n)if (n == 0)return 1;} elseint result = 1;for (int i = 1; i <= n; i++) result *= i;}return result;}}//组合运算if (n >= r)return factorial(n) / (factorial(r) * factorial(n - r));} elsecout << "Error: Invalid input!" << endl;return 0;}}};//主函数int maiScientificCalculator calculator;//进行一些简单的计算cout << "Addition: " << calculator.add(5, 3) << endl;cout << "Subtraction: " << calculator.subtract(5, 3) << endl;cout << "Multiplication: " << calculator.multiply(5, 3) << endl;cout << "Division: " << calculator.divide(5, 3) << endl;//三角函数运算cout << "Sine: " << calculator.sine(0.5) << endl;cout << "Cosine: " << calculator.cosine(0.5) << endl;cout << "Tangent: " << calculator.tangent(0.5) << endl;//指数和对数运算cout << "Exponent: " << calculator.exponent(2) << endl;cout << "Logarithm: " << calculator.logarithm(100) << endl;//阶乘和组合运算cout << "Factorial: " << calculator.factorial(5) << endl;return 0;```这个科学计算器的源代码使用了面向对象的编程思想,将不同的数学运算封装成类的成员函数。

实用计算器的程序设计及代码示例

实用计算器的程序设计及代码示例

实用计算器的程序设计及代码示例计算器是现代人经常使用的工具,它能够进行各种数学运算,如加减乘除、取余、开方等。

本文将介绍实用计算器的程序设计和提供代码示例,帮助读者了解计算器的原理和实现方式。

一、程序设计思路在设计实用计算器的程序时,首先需要确定计算器的功能和界面设计。

一般来说,一个基本的计算器应该具备以下功能:数字键、运算符键、等号键、清除键和显示屏。

程序的设计思路如下:1. 定义一个变量num,用于保存当前输入的数字。

2. 定义一个变量result,用于保存计算结果。

3. 通过按钮点击事件,获取用户输入的数字和运算符,并根据用户的选择进行相应的计算。

4. 将计算结果显示在显示屏上。

二、代码示例下面是一个简单的实用计算器程序的代码示例,采用Python语言编写:```from tkinter import *def clear():display.delete(0, END)def calculate():expression = display.get()result = eval(expression)display.delete(0, END)display.insert(0, result)def button_click(number):current = display.get()display.delete(0, END)display.insert(0, str(current) + str(number))root = Tk()root.title("实用计算器")display = Entry(root, width=25, borderwidth=5)display.grid(row=0, column=0, columnspan=4, padx=10, pady=10)button_1 = Button(root, text="1", padx=10, pady=10, command=lambda: button_click(1))button_2 = Button(root, text="2", padx=10, pady=10, command=lambda: button_click(2))button_3 = Button(root, text="3", padx=10, pady=10, command=lambda: button_click(3))button_4 = Button(root, text="4", padx=10, pady=10, command=lambda: button_click(4))button_5 = Button(root, text="5", padx=10, pady=10, command=lambda: button_click(5))button_6 = Button(root, text="6", padx=10, pady=10, command=lambda: button_click(6))button_7 = Button(root, text="7", padx=10, pady=10, command=lambda: button_click(7))button_8 = Button(root, text="8", padx=10, pady=10, command=lambda: button_click(8))button_9 = Button(root, text="9", padx=10, pady=10, command=lambda: button_click(9))button_0 = Button(root, text="0", padx=10, pady=10, command=lambda: button_click(0))button_add = Button(root, text="+", padx=10, pady=10,command=lambda: button_click("+"))button_subtract = Button(root, text="-", padx=10, pady=10,command=lambda: button_click("-"))button_multiply = Button(root, text="*", padx=10, pady=10, command=lambda: button_click("*"))button_divide = Button(root, text="/", padx=10, pady=10, command=lambda: button_click("/"))button_clear = Button(root, text="C", padx=10, pady=10, command=clear)button_equal = Button(root, text="=", padx=10, pady=10, command=calculate)button_1.grid(row=1, column=0)button_2.grid(row=1, column=1)button_3.grid(row=1, column=2)button_add.grid(row=1, column=3)button_4.grid(row=2, column=0)button_5.grid(row=2, column=1)button_6.grid(row=2, column=2)button_subtract.grid(row=2, column=3)button_7.grid(row=3, column=0)button_8.grid(row=3, column=1)button_9.grid(row=3, column=2)button_multiply.grid(row=3, column=3)button_0.grid(row=4, column=0)button_clear.grid(row=4, column=1)button_equal.grid(row=4, column=2)button_divide.grid(row=4, column=3)root.mainloop()```以上代码使用了`tkinter`库创建了一个简单的图形界面,包含数字按钮、运算符按钮、清除按钮和等于按钮。

计算器源代码

计算器源代码
#define NUM5 0x4c35 /* 小键盘区上数字键5 */
#define NUM6 0x4d36 /* 小键盘区上数字键6 */
#define NUM7 0x4737 /* 小键盘区上数字键7 */
#define NUM8 0x4838 /* 小键盘区上数字键8 */
void CommandButton_KeyboardUp(int i); /*定义松开编号为i的按键所进行的操作,如按钮的状态*/
void InitApp(); /*初始化程序*/
void Showme(); /*显示计算器界面*/
void Load(); /*初始化默认值*/
case F9: key=11;break;
case NUMPNT:case KEYPNT: key=12;break;
case NUMADD: key=13;break;
#include "graphics.h" /* 图形函数库 */
#include "bios.h" /* 基本输入输出系统函数库*/
#include "dos.h" /* dos函数库 */
#define NUM0 0x5230 /* 小键盘区上数字键0 */
#define KEY5 0x635 /* 主键盘区上数字键5 */
#define KEY6 0x736 /* 主键盘区上数字键6 */
#define KEY7 0x837 /* 主键盘区上数字键7 */
#define KEY8 0x938 /* 主键盘区上数字键8 */
int top,pointflag,digitkeyhit; /*top:保存缓冲区中的当前位数,pointflag:小数点标记,digitkeyhit:数字键按键标记*/

C语言计算器程序源代码

C语言计算器程序源代码

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

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

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

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

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档