科学计算器源代码
- 格式:doc
- 大小:56.50 KB
- 文档页数:13
计算器源代码'请把下面的保存为form1.frmVERSION 5.00Begin VB.Form CalculatorBorderStyle = 1 'Fixed SingleCaption = "计算器"ClientHeight = 2970ClientLeft = 2580ClientTop = 1485ClientWidth = 3270ClipControls = 0 'FalseBeginProperty FontName = "System "Size = 9.75Charset = 0Weight = 700Underline = 0 'FalseItalic = 0 'FalseStrikethrough = 0 'False EndPropertyIcon = "CALC.frx ":0000 LinkMode = 1 'SourceLinkTopic = "Form1 "MaxButton = 0 'FalsePaletteMode = 1 'UseZOrderScaleHeight = 2970ScaleWidth = 3270WhatsThisHelp = -1 'TrueBegin mandButton NumberCaption = "7 "Height = 480Index = 7Left = 120TabIndex = 7Top = 600Width = 480 EndBegin mandButton NumberCaption = "8 "Height = 480Index = 8Left = 720TabIndex = 8Width = 480 EndBegin mandButton NumberCaption = "9 "Height = 480Index = 9Left = 1320TabIndex = 9Top = 600Width = 480 EndBegin mandButton CancelCaption = "C "Height = 480Left = 2040TabIndex = 10Top = 600Width = 480 EndBegin mandButton CancelEntry Caption = "CE "Height = 480Left = 2640TabIndex = 11Top = 600Width = 480 EndBegin mandButton NumberCaption = "4 "Height = 480Index = 4Left = 120TabIndex = 4Top = 1200Width = 480 EndBegin mandButton NumberCaption = "5 "Height = 480Index = 5Left = 720TabIndex = 5Top = 1200EndBegin mandButton NumberCaption = "6 "Height = 480Index = 6Left = 1320TabIndex = 6Top = 1200Width = 480 EndBegin mandButton Operator Caption = "+ "Height = 480Index = 1Left = 2040TabIndex = 12Top = 1200Width = 480 EndBegin mandButton Operator Caption = "- "Height = 480Index = 3Left = 2640TabIndex = 13Top = 1200Width = 480 EndBegin mandButton NumberCaption = "1 "Height = 480Index = 1Left = 120TabIndex = 1Top = 1800Width = 480 EndBegin mandButton NumberCaption = "2 "Height = 480Index = 2Left = 720TabIndex = 2Width = 480 EndBegin mandButton NumberCaption = "3 "Height = 480Index = 3Left = 1320TabIndex = 3Top = 1800Width = 480 EndBegin mandButton Operator Caption = "X "Height = 480Index = 2Left = 2040TabIndex = 14Top = 1800Width = 480 EndBegin mandButton Operator Caption = "/ "Height = 480Index = 0Left = 2640TabIndex = 15Top = 1800Width = 480 EndBegin mandButton NumberCaption = "0 "Height = 480Index = 0Left = 120TabIndex = 0Top = 2400Width = 1080 EndBegin mandButton Decimal Caption = ". "Height = 480Left = 1320TabIndex = 18Width = 480EndBegin mandButton OperatorCaption = "= "Height = 480Index = 4Left = 2040TabIndex = 16Top = 2400Width = 480EndBegin mandButton PercentCaption = "% "Height = 480Left = 2640TabIndex = 17Top = 2400Width = 480EndBegin bel ReadoutAlignment = 1 'Right JustifyBackColor = &H0000FFFF&BorderStyle = 1 'Fixed SingleCaption = "0. "BeginProperty FontName = "MS Sans Serif "Size = 12Charset = 0Weight = 700Underline = 0 'FalseItalic = 0 'FalseStrikethrough = 0 'FalseEndPropertyForeColor = &H00000000&Height = 375Left = 120TabIndex = 19Top = 105Width = 3000EndEndAttribute VB_Name = "Calculator "Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption ExplicitDim Op1, Op2 ' 前面输入的操作数Dim DecimalFlag As Integer ' 小数点仍然存在吗?Dim NumOps As Integer ' 操作数个数Dim LastInput ' 指示上一次按键事件的类型Dim OpFlag ' 指示未完成的操作Dim TempReadout' C (取消) 按钮的Click 事件过程' 重新设置显示并初始化变量Private Sub Cancel_Click()Readout = Format(0, "0. ")Op1 = 0Op2 = 0Form_LoadEnd Sub' CE (取消输入) 按钮的Click 事件过程Private Sub CancelEntry_Click()Readout = Format(0, "0. ")DecimalFlag = FalseLastInput = "CE "End Sub' 小数点(.) 按钮的Click 事件过程' 如果上一次按键为运算符,初始化readout 为"0. ";' 否则显示时追加一个小数点Private Sub Decimal_Click()If LastInput = "NEG " ThenReadout = Format(0, "-0. ")ElseIf LastInput <> "NUMS " ThenReadout = Format(0, "0. ")End IfDecimalFlag = TrueLastInput = "NUMS "End Sub' 窗体的初始化过程' 设置所有变量为其初始值Private Sub Form_Load()DecimalFlag = FalseNumOps = 0LastInput = "NONE "OpFlag = " "Readout = Format(0, "0. ")'Decimal.Caption = Format(0, ". ")End Sub' 数字键(0-9) 的Click 事件过程' 向显示中的数追加新数Private Sub Number_Click(Index As Integer)If LastInput <> "NUMS " ThenReadout = Format(0, ". ")DecimalFlag = FalseEnd IfIf DecimalFlag ThenReadout = Readout + Number(Index).CaptionElseReadout = Left(Readout, InStr(Readout, Format(0, ". ")) - 1) + Number(Index).Caption + Format(0, ". ")End IfIf LastInput = "NEG " Then Readout = "- " & ReadoutLastInput = "NUMS "End Sub' 运算符(+, -, x, /, =) 的Click 事件过程' 如果接下来的按键是数字键,增加NumOps。
python简易计算器程序代码Python简易计算器程序代码Python是一种高级编程语言,它可以用于开发各种类型的应用程序,包括计算器。
在本文中,我们将介绍如何使用Python编写一个简单的计算器程序。
我们需要定义一个函数来执行计算操作。
这个函数将接收两个参数:操作符和操作数。
操作符可以是加号、减号、乘号或除号,操作数可以是任何数字。
def calculate(operator, operand1, operand2):if operator == '+':return operand1 + operand2elif operator == '-':return operand1 - operand2elif operator == '*':return operand1 * operand2elif operator == '/':return operand1 / operand2接下来,我们需要编写一个主函数来获取用户输入并调用calculate 函数来执行计算操作。
我们将使用一个while循环来持续获取用户输入,直到用户输入“exit”为止。
def main():while True:operator = input("Enter operator (+, -, *, /): ")if operator == 'exit':breakoperand1 = float(input("Enter first operand: "))operand2 = float(input("Enter second operand: "))result = calculate(operator, operand1, operand2)print("Result: ", result)我们需要调用主函数来启动程序。
JAVA编写的计算器源代码// Calculator.javaimport javax.swing.*; // 引入swing库import java.awt.*; // 引入awt库import java.awt.event.*; // 引入awt.event库public class Calculator extends JFrame implements ActionListener//定义按钮private JButton zero;private JButton one;private JButton two;private JButton three;private JButton four;private JButton five;private JButton six;private JButton seven;private JButton eight;private JButton nine;private JButton point;private JButton equal; private JButton plus; private JButton minus; private JButton multiply; private JButton divide; private JButton backspace; private JButton ac;private JButton ce;private JButton sqrt; private JButton sqr;private JButton plus_minus; private JButton delete; private JButton sin;private JButton cos;private JButton tan;private JButton log;private JButton nfactorial; private JButton cubic; private JButton coln;private JButton factorial;//定义文本框private JTextField resulttext;// 定义boolean变量boolean clrdisp = true; // 昵称确定是否清除计算器显示boolean isCalculate = false; // 是否可以执行计算// 定义String变量,用于存储操作符String optr;//定义存储第一个操作数double num1;//初始化构造函数public Calculato//设置布局setLayout(new BorderLayout();//创建面板JPanel northPanel = new JPanel(;JPanel centerPanel = new JPanel(;JPanel southPanel = new JPanel(;//设置面板布局northPanel.setLayout(new FlowLayout(); centerPanel.setLayout(new GridLayout(4, 5)); southPanel.setLayout(new FlowLayout();//设置计算器显示resulttext = new JTextField(28); northPanel.add(resulttext);resulttext.setEditable(false);//初始化按钮zero = new JButton("0");one = new JButton("1");two = new JButton("2");three = new JButton("3");four = new JButton("4");five = new JButton("5");six = new JButton("6");seven = new JButton("7");eight = new JButton("8");nine = new JButton("9");point = new JButton(".");equal = new JButton("=");plus = new JButton("+");minus = new JButton("-"); multiply = new JButton("*"); divide = new JButton("/"); backspace = new JButton("<-"); ac = new JButton("AC");ce = new JButton("CE");sqrt = new JButton("sqrt");sqr = new JButton("sqr");plus_minus = new JButton("+/-");。
超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用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 System.Windows.Forms;using System.Data;namespace Calc{///<summary>/// QQ:479340056 温柔一刀C#简易计算器的实现///</summary>public class CalcForm : System.Windows.Forms.Form{private System.Windows.Forms.Button btn_0;private System.Windows.Forms.Button btn_1;private System.Windows.Forms.Button btn_2;private System.Windows.Forms.Button btn_3;private System.Windows.Forms.Button btn_4;private System.Windows.Forms.Button btn_5;private System.Windows.Forms.Button btn_6;private System.Windows.Forms.Button btn_7;private System.Windows.Forms.Button btn_8;private System.Windows.Forms.Button btn_9;private System.Windows.Forms.Button btn_add;private System.Windows.Forms.Button btn_sub;private System.Windows.Forms.Button btn_mul;private System.Windows.Forms.Button btn_div;private System.Windows.Forms.Button btn_sqrt;private System.Windows.Forms.Button btn_sign;private System.Windows.Forms.Button btn_equ;private System.Windows.Forms.Button btn_dot;private System.Windows.Forms.Button btn_rev;private System.Windows.Forms.TextBox txtShow;private System.Windows.Forms.Button btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;///<summary>///必需的设计器变量。
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();}}。
程序功能简介:从最基本的加、减、乘、除,到基本数学函数处理,再到数的进制转换处理。
代码如下/*文件名:Calculator.java*说明:简易科学计算器*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends Frame implements ActionListener, WindowListener{private Container container;private GridBagLayout layout;private GridBagConstraints constraints;private JTextField displayField; //计算结果显示区private String lastCommand; //保存+,-,*,/,=命令0private double result; //保存计算结果private boolean start; //判断是否为数字的开始private JMenuBar menubar;private JMenuItem m_exit,m2_ejz,m2_bjz;private Dialog dialog;private Label label_dialog;private JButton button_sqrt,button_plusminus,button_CE,button_cancel,button_1,button_2,button_3,button_4,button_5,button_6,button_7,button_8,button_9,button_0,button_plus,button_minus,button_multiply,button_divide,button_point,button_equal,button_log,button_tan,button_cos,button_sin,button_exp;public Calculator() //构造方法设置布局、为按钮注册事件监听器{super("Calculator");this.setLocation(240,200);this.setSize(350,300);this.setResizable(true);this.setLayout(new GridLayout(7,1));this.addmyMenu(); //调用成员方法添加菜单displayField=new JTextField(30);this.add(displayField);displayField.setEditable(true);start=true;result=0;lastCommand = "=";JPanel panel0=new JPanel();panel0.setLayout(new GridLayout(1,4,4,4));JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(1,5,4,4));this.add(panel1);button_sqrt=new JButton("sqrt");button_plusminus=new JButton("+/-");button_exp=new JButton("exp");button_CE=new JButton("退格");button_cancel=new JButton("C");JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,5,4,4));this.add(panel2);button_7=new JButton("7");button_8=new JButton("8");button_9=new JButton("9");button_log=new JButton("log");button_divide=new JButton("/");JPanel panel3=new JPanel();panel3.setLayout(new GridLayout(1,5,4,4));this.add(panel3);button_4=new JButton("4");button_5=new JButton("5");button_6=new JButton("6");button_tan=new JButton("tan");button_multiply=new JButton("*");JPanel panel4=new JPanel();panel4.setLayout(new GridLayout(1,5,4,4));this.add(panel4);button_1=new JButton("1");button_2=new JButton("2");button_3=new JButton("3");button_cos=new JButton("cos");button_minus=new JButton("-");JPanel panel5=new JPanel();panel5.setLayout(new GridLayout(1,5,4,4));this.add(panel5);button_0=new JButton("0");button_point=new JButton(".");button_equal=new JButton("=");button_sin=new JButton("sin");button_plus=new JButton("+");panel1.add(button_sqrt);panel1.add(button_plusminus);panel1.add(button_exp);panel1.add(button_CE);panel1.add(button_cancel);panel2.add(button_7);panel2.add(button_8);panel2.add(button_9);panel2.add(button_log);panel2.add(button_divide);panel3.add(button_4);panel3.add(button_5);panel3.add(button_6);panel3.add(button_tan);panel3.add(button_multiply);panel4.add(button_1);panel4.add(button_2);panel4.add(button_3);panel4.add(button_cos);panel4.add(button_minus);panel5.add(button_0);panel5.add(button_point);panel5.add(button_equal);panel5.add(button_sin);panel5.add(button_plus);button_sqrt.addActionListener(this);button_plusminus.addActionListener(this);button_exp.addActionListener(this);button_CE.addActionListener(this);button_cancel.addActionListener(this);button_7.addActionListener(this);button_8.addActionListener(this);button_9.addActionListener(this);button_log.addActionListener(this);button_divide.addActionListener(this);button_4.addActionListener(this);button_5.addActionListener(this);button_6.addActionListener(this);button_tan.addActionListener(this);button_multiply.addActionListener(this);button_1.addActionListener(this);button_2.addActionListener(this);button_3.addActionListener(this);button_cos.addActionListener(this);button_minus.addActionListener(this);button_0.addActionListener(this);button_point.addActionListener(this);button_equal.addActionListener(this);button_sin.addActionListener(this);button_plus.addActionListener(this);this.addWindowListener(new WinClose()); //注册窗口监听器this.setVisible(true);}private void addmyMenu() //菜单的添加{JMenuBar menubar=new JMenuBar();this.add(menubar);JMenu m1=new JMenu("选项");JMenu m2=new JMenu("进制转换");JMenuItem m1_exit=new JMenuItem("退出");m1_exit.addActionListener(this);JMenuItem m2_ejz=new JMenuItem("二进制");m2_ejz.addActionListener(this);JMenuItem m2_bjz=new JMenuItem("八进制");m2_bjz.addActionListener(this);JMenu m3 = new JMenu(" 帮助");JMenuItem m3_Help = new JMenuItem("用法");m3_Help.addActionListener(this);dialog = new Dialog(this,"提示",true); //模式窗口dialog.setSize(240,80);label_dialog = new Label("",Label.CENTER); //标签的字符串为空,居中对齐dialog.add(label_dialog);dialog.addWindowListener(this); //为对话框注册窗口事件监听器m1.add(m1_exit);menubar.add(m1);m2.add(m2_ejz);m2.add(m2_bjz);menubar.add(m2);m3.add(m3_Help);menubar.add(m3); }public void actionPerformed(ActionEvent e) //按钮的单击事件处理方法{if(e.getSource().equals(button_1)||e.getSource().equals(button_2)||e.getSource().equals(button_3)||e.getSource().equals(button_4)||e.getSource().equals(button_5)|| e.getSource().equals(button_6)||e.getSource().equals(button_7)|| e.getSource().equals(button_8)||e.getSource().equals(button_9) ||e.getSource().equals(button_0)||e.getSource().equals(button_point)||e.getSource().equals(button_plusminus)||e.getSource().equals(button_cancel)||e.getSource().equals(button_CE)){ //非运算符的处理方法String input=e.getActionCommand();if (start){displayField.setText("");start=false;if(input.equals("+/-"))displayField.setText(displayField.getText()+"-");}if(!input.equals("+/-")){String str=displayField.getText();if(input.equals("退格")) //退格键的实现方法{if(str.length()>0)displayField.setText(str.substring(0,str.length()-1));}else if(input.equals("C")) //清零键的实现方法{displayField.setText("0");start=true;}elsedisplayField.setText(displayField.getText()+input);}}else if (e.getActionCommand()=="二进制") //二进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toBinaryString(n));}else if (e.getActionCommand()=="八进制") //八进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toOctalString(n));}else if (e.getActionCommand()=="退出") //选项中退出的处理方法{System.exit(0);}else if (e.getActionCommand()=="用法") //按下'帮助'菜单栏中用法的处理方法{label_dialog.setText("sqrt,exp等键是先输运算符再输数字\n");dialog.setLocation(400,250);dialog.setVisible(true);}else //各运算符的识别{String command=e.getActionCommand();if(start){lastCommand=command;}else{calculate(Double.parseDouble(displayField.getText()));lastCommand=command;start=true;}}}public void calculate(double x) //各运算符的具体运算方法double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}displayField.setText(""+ result);}public void windowClosing(WindowEvent e){if(e.getSource()==dialog)dialog.setVisible(false); //隐藏对话框 elseSystem.exit(0);public void windowOpened(WindowEvent e) { }public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }public void windowClosed(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public static void main(String args[]){Calculator calculator=new Calculator();}}class WinClose implements WindowListener{public void windowClosing(WindowEvent e) //单击窗口关闭按钮时触发并执行实现窗口监听器接口中的方法{System.exit(0); //结束程序运行}public void windowOpened(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}}运行结果截图:程序功能实现:1.运用两个面板的叠加做出界面。
//计算器,已经编译通过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();}}。
计算器vb源代码.txt性格本身没有好坏,乐观和悲观对这个世界都有贡献,前者发明了飞机,后者发明了降落伞。
完全版的前后台代码...'请把下面的保存为VERSIONBegin CalculatorBorderStyle = 1 'Fixed SingleCaption = "计算器"ClientHeight = 2970ClientLeft = 2580ClientTop = 1485ClientWidth = 3270ClipControls = 0 'FalseBeginProperty FontName = "System"Size =Charset = 0Weight = 700Underline = 0 'FalseItalic = 0 'FalseStrikethrough = 0 'FalseEndPropertyIcon = "":0000LinkMode = 1 'SourceLinkTopic = "Form1"MaxButton = 0 'FalsePaletteMode = 1 'UseZOrderScaleHeight = 2970ScaleWidth = 3270WhatsThisHelp = -1 'TrueBegin NumberCaption = "7"Height = 480Index = 7Left = 120TabIndex = 7Top = 600Width = 480EndBegin NumberCaption = "8"Index = 8Left = 720TabIndex = 8Top = 600Width = 480 EndBegin NumberCaption = "9"Height = 480Index = 9Left = 1320TabIndex = 9Top = 600Width = 480 EndBegin CancelCaption = "C"Height = 480Left = 2040TabIndex = 10Top = 600Width = 480 EndBegin CancelEntryCaption = "CE"Height = 480Left = 2640TabIndex = 11Top = 600Width = 480 EndBegin NumberCaption = "4"Height = 480Index = 4Left = 120TabIndex = 4Top = 1200Width = 480 EndBegin NumberCaption = "5"Index = 5Left = 720TabIndex = 5Top = 1200Width = 480 EndBegin NumberCaption = "6"Height = 480Index = 6Left = 1320TabIndex = 6Top = 1200Width = 480 EndBegin OperatorCaption = "+"Height = 480Index = 1Left = 2040TabIndex = 12Top = 1200Width = 480 EndBegin OperatorCaption = "-"Height = 480Index = 3Left = 2640TabIndex = 13Top = 1200Width = 480 EndBegin NumberCaption = "1"Height = 480Index = 1Left = 120TabIndex = 1Top = 1800Width = 480 EndBegin NumberCaption = "2"Height = 480Index = 2Left = 720TabIndex = 2Top = 1800Width = 480 EndBegin NumberCaption = "3"Height = 480Index = 3Left = 1320TabIndex = 3Top = 1800Width = 480 EndBegin OperatorCaption = "X"Height = 480Index = 2Left = 2040TabIndex = 14Top = 1800Width = 480 EndBegin OperatorCaption = "/"Height = 480Index = 0Left = 2640TabIndex = 15Top = 1800Width = 480 EndBegin NumberCaption = "0"Height = 480Index = 0Left = 120TabIndex = 0Top = 2400EndBegin DecimalCaption = "."Height = 480Left = 1320TabIndex = 18Top = 2400Width = 480EndBegin OperatorCaption = "="Height = 480Index = 4Left = 2040TabIndex = 16Top = 2400Width = 480EndBegin PercentCaption = "%"Height = 480Left = 2640TabIndex = 17Top = 2400Width = 480EndBegin ReadoutAlignment = 1 'Right JustifyBackColor = &H0000FFFF&BorderStyle = 1 'Fixed SingleCaption = "0."BeginProperty FontName = "MS Sans Serif"Size = 12Charset = 0Weight = 700Underline = 0 'FalseItalic = 0 'FalseStrikethrough = 0 'FalseEndPropertyForeColor = &H00000000&Height = 375TabIndex = 19Top = 105Width = 3000EndEndAttribute VB_Name = "Calculator"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = False' --------------------------------------------------------------------------' 版权所有(C) 1994 Microsoft Corporation'' 您可以免费以任何方式使用、修改、复制并分发您认为有用的' 示例应用程序文件(或任何修改过的版本)。
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科学计算器{public partial class Form1 : Form{protected double iNum1,into;protected char cOperator;protected bool bNumBegins;protected bool bDot;protected double iMem;public Form1(){InitializeComponent();InitMembers();}private void InitMembers(){iNum1 = 0.0;cOperator = '=';bNumBegins = true;bDot = false;}private void Numbers_Click(double i){if (txtOutput.Text == "Error"){txtOutput.Text = "0";}try{if (bNumBegins){txtOutput.Text = i.ToString();bNumBegins = false;}else{txtOutput.Text += i.ToString();}double iCurrent = double.Parse(txtOutput.Text);}catch{txtOutput.Text = "Error";InitMembers();return;}}private void Operators_Click(char op){double iCurrent;try{iCurrent = double.Parse(txtOutput.Text);}catch{txtOutput.Text = "Error";InitMembers();return;}double iResult;try{switch(cOperator ){case'+':checked {iResult =iNum1 +iCurrent ;}break;case'-':checked {iResult =iNum1 -iCurrent ;}break;case'*':checked {iResult =iNum1 *iCurrent ;}break;case'/':checked {iResult =iNum1 *iCurrent ;}break;default :iResult = iCurrent;break;}}catch{txtOutput.Text = "Error";InitMembers();return;}txtOutput.Text = iResult.ToString();iNum1 = iResult;bNumBegins = true;bDot = false;cOperator = op;}private void Dot_Click(object sender,EventArgs e) {if (bDot){txtOutput.Text = "Error";InitMembers ();return;}else if (bNumBegins){txtOutput.Text = "0";bNumBegins = false;bDot = true;}elsetxtOutput.Text += '.';bDot = true;}private void btnCancel_Click(object sender,System.EventArgs e){txtOutput.Text = "0";InitMembers();return;}public string dot(int d){string b = "";//判断该数如果小于2,则直接输出if (d < 2){b = d.ToString();}else{int c;int s = 0;int n = d;while (n >= 2){s++;n = n / 2;}int[] m = new int[s];int i = 0;do{c =d / 2;m[i++] = d % 2;d = c;} while (c >= 2);b = d.ToString();for (int j = m.Length - 1; j >= 0; j--){b += m[j].ToString();}}return b;}public string dox(int d){string x = "";if (d < 8){x = d.ToString();}else{int c;int s = 0;int n = d;while (n >= 8){s++;n = n / 8;}int[] m = new int[s];int i = 0;do{c =d / 8;m[i++] = d % 8;d = c;} while (c >= 8);x = d.ToString();for (int j = m.Length - 1; j >= 0; j--){x += m[j];}}return x;}//十进制转十六进制public string doy(int d){string x = "";if (d < 16){x = chang(d);}else{int c;int s = 0;int n = d;while (n >= 16){s++;n = n / 16;}string[] m = new string[s];int i = 0;do{c =d / 16;m[i++] = chang(d % 16);//判断是否大于10,如果大于10,则转换为A~F的格式d = c;}while (c >= 16);x = chang(d);for (int j = m.Length - 1; j >= 0; j--){x += m[j];}}return x;}//判断是否为10~15之间的数,如果是则进行转换public string chang(int d){string x = "";switch (d){case 10:x = "A";break;case 11:x = "B";break;case 12:x = "C";break;case 13:x = "D";break;case 14:x = "E";break;case 15:x = "F";break;default:x = d.ToString();break;}return x;}protected void ResetState(){bNumBegins =true ;cOperator ='=';}[STAThread]private void button1_Click(object sender, EventArgs e) {Numbers_Click(1);}private void button2_Click(object sender, EventArgs e) {Numbers_Click(2);}private void button3_Click(object sender, EventArgs e) {Numbers_Click(3);}private void button4_Click(object sender, EventArgs e) {Numbers_Click(4);}private void button5_Click(object sender, EventArgs e) {Numbers_Click(5);}private void button6_Click(object sender, EventArgs e) {Numbers_Click(6);}private void bttton7_Click(object sender, EventArgs e) {Numbers_Click(7);}private void button8_Click(object sender, EventArgs e) {Numbers_Click(8);}private void button9_Click(object sender, EventArgs e) {Numbers_Click(9);}private void button0_Click(object sender, EventArgs e) {Numbers_Click(0);}private void btnAdd_Click(object sender, EventArgs e) {Operators_Click('+');}private void btnSubstract_Click(object sender, EventArgs e) {Operators_Click('-');}private void btnMultiply_Click(object sender, EventArgs e) {Operators_Click('*');}private void btnDivide_Click(object sender, EventArgs e) {Operators_Click('/');}private void btnEquals_Click(object sender, EventArgs e) {Operators_Click('=');}private void Dot_Click_1(object sender, EventArgs e){if (bDot){txtOutput.Text = "Error";InitMembers();return;}else if (bNumBegins){txtOutput.Text = "0";bNumBegins = false;bDot = true;}elsetxtOutput.Text += '.';bDot = true;}private void btnCancel_Click_1(object sender, EventArgs e) {txtOutput.Text = "0";InitMembers();return;}private void btnMC_Click(object sender, EventArgs e) {iMem = 0;lblMem.Visible = false;ResetState();}private void btnMR_Click(object sender, EventArgs e) {if (lblMem.Visible){txtOutput.Text = iMem.ToString();bNumBegins = true;}}private void btnMS_Click(object sender, EventArgs e){try{iMem = 0;iMem = double.Parse(txtOutput.Text);if (iMem != 0){lblMem.Visible = true;ResetState();}}catch{}}private void btnMAdd_Click(object sender, EventArgs e) {try{checked { iMem += long.Parse(txtOutput.Text); }lblMem.Visible = true;ResetState();}catch{txtOutput.Text = "Error";}}private void btnsin_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);into = into * (Math.PI) / 180;txtOutput.Text = Math.Sin(into).ToString();}private void btncos_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);into = into * (Math.PI) / 180;txtOutput.Text = Math.Cos(into).ToString();}private void btntan_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);into = into * (Math.PI) / 180;txtOutput.Text = Math.Tan(into).ToString();}private void正割_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);into = into * (Math.PI) / 180;txtOutput.Text = (1 / Math.Cos(into)).ToString();}private void余割_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);into = into * (Math.PI) / 180;txtOutput.Text = (1 / Math.Sin(into)).ToString();}private void余切_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);into = into * (Math.PI) / 180;txtOutput.Text = Math.Tan(into).ToString();}private void二进制_Click(object sender, EventArgs e){txtOutput.Text = dot(Convert.ToInt32(txtOutput.Text));//十进制转化为二进制}private void八进制_Click(object sender, EventArgs e){txtOutput.Text = dox(Convert.ToInt32(txtOutput.Text));//十进制转化为八进制}private void十六进制_Click(object sender, EventArgs e){txtOutput.Text = doy(Convert.ToInt32(txtOutput.Text));//十进制转化为十六进制}private void圆周率_Click(object sender, EventArgs e){txtOutput.Text = Math.PI.ToString();}private void btnln_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);txtOutput.Text = Math.Log10(into).ToString();}private void btnlg_Click(object sender, EventArgs e){into = double.Parse(txtOutput.Text);txtOutput.Text = Math.Log(into).ToString();}}}。
package two; import java.awt.*; import javax.swing.*;
import java.awt.event.*; import java.io.*; import java.util.*;
public class calculator implements ActionListener { int count = 0; private static int a; JFrame frame = new JFrame("计算器"); JTextArea area = new JTextArea(); JTextField fieldshow = new JTextField("0"); JTextField fieldcalculator = new JTextField(); JPanel leftpanel = new JPanel(); JPanel rightpanel = new JPanel(); JPanel buttonpanel = new JPanel(); JPanel motionpanel = new JPanel(); JButton button1 = new JButton("1"); JButton button2 = new JButton("2"); JButton button3 = new JButton("3"); JButton button4 = new JButton("+"); JButton button5 = new JButton("c"); JButton button6 = new JButton("4"); JButton button7 = new JButton("5"); JButton button8 = new JButton("6"); JButton button9 = new JButton("-"); JButton button10 = new JButton("退格"); JButton button11 = new JButton("7"); JButton button12 = new JButton("8"); JButton button13 = new JButton("9"); JButton button14 = new JButton("*"); JButton button15 = new JButton("sin"); JButton button16 = new JButton("0"); JButton button17 = new JButton("+/-"); JButton button18 = new JButton("."); JButton button19 = new JButton("/"); JButton button20 = new JButton("="); JButton button21 = new JButton("保存"); JButton button22 = new JButton("复制"); JButton button23 = new JButton("清除"); StringBuffer S = new StringBuffer(""); // t用来记录前一个运算符号是+ - * / =中的哪一个 char t; // count用来实现运算符号计数,a用来识别退格、正负号操作前一个操作是否是运算符号+ - * / sin = // int count = 0, a = 0; Double x1, x2 = 0d, result;
public static void main(String a[]) { calculator that = new calculator(); that.go(); }
void go() { leftpanel.setLayout(new BorderLayout()); leftpanel.add(fieldshow, BorderLayout.NORTH); leftpanel.add(buttonpanel, BorderLayout.CENTER);
buttonpanel.setLayout(new GridLayout(4, 5)); buttonpanel.add(button1); buttonpanel.add(button2); buttonpanel.add(button3); buttonpanel.add(button4); buttonpanel.add(button5); buttonpanel.add(button6); buttonpanel.add(button7); buttonpanel.add(button8); buttonpanel.add(button9); buttonpanel.add(button10); buttonpanel.add(button11); buttonpanel.add(button12); buttonpanel.add(button13); buttonpanel.add(button14); buttonpanel.add(button15); buttonpanel.add(button16); buttonpanel.add(button17); buttonpanel.add(button18); buttonpanel.add(button19); buttonpanel.add(button20);
button1.addActionListener(this);// 事件监听 button2.addActionListener(this); button3.addActionListener(this); button4.addActionListener(this); button5.addActionListener(this); button6.addActionListener(this); button7.addActionListener(this); button8.addActionListener(this); button9.addActionListener(this); button10.addActionListener(this); button11.addActionListener(this); button12.addActionListener(this); button13.addActionListener(this); button14.addActionListener(this); button15.addActionListener(this); button16.addActionListener(this); button17.addActionListener(this); button18.addActionListener(this); button19.addActionListener(this); button20.addActionListener(this); button21.addActionListener(this); button22.addActionListener(this); button23.addActionListener(this);
rightpanel.setLayout(new BorderLayout()); rightpanel.add(fieldcalculator, BorderLayout.NORTH); rightpanel.add(area, BorderLayout.CENTER); rightpanel.add(motionpanel, BorderLayout.SOUTH);
motionpanel.add(button21); motionpanel.add(button22); motionpanel.add(button23);
Container con = frame.getContentPane(); frame.setLayout(new GridLayout(1, 2)); con.add(leftpanel); con.add(rightpanel);
frame.setBounds(200, 200, 600, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowListener() {// 关闭程序时弹出警告 public void windowClosing(WindowEvent e) { int result = JOptionPane.showConfirmDialog(frame, "确实要关闭程序吗?", "警告", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_CANCEL_OPTION) { System.exit(0); } else { } } public void windowOpened(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowActivated(WindowEvent e) {} });
} public void actionPerformed(ActionEvent e) { // 0123456789等按钮 if (e.getSource() == button1 || e.getSource() == button2 || e.getSource() == button3 || e.getSource() == button6 || e.getSource() == button7 || e.getSource() == button8 || e.getSource() == button11 || e.getSource() == button12 || e.getSource() == button13 || e.getSource() == button16) { a = 0; if (count == 0) { S.append(e.getActionCommand()); fieldshow.setText(S.toString()); x1 = Double.parseDouble(fieldshow.getText()); } else if (count >= 1) { S.append(e.getActionCommand()); fieldshow.setText(S.toString()); x2 = Double.parseDouble(fieldshow.getText()); }