《计算器源代码》Word文档
简易计算器程序源代码
简易计算器程序源代码下面是一个简易计算器程序的源代码,它可以执行基本的四则运算:```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("请输入有效的选择")```运行这个程序,你将看到一个简易的计算器菜单。
简单的计算器源代码
ห้องสมุดไป่ตู้
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());
C语言计算器源代码
C语言计算器源代码下面是一个简单的C语言计算器源代码:```c#include<stdio.h>int mainfloat num1, num2, result;char operator;printf("请输入两个数字:");scanf("%f %f", &num1, &num2);printf("请选择运算符(+,-,*,/):"); scanf(" %c", &operator);switch(operator)case '+':result = num1 + num2;printf("结果: %.2f\n", result);break;case '-':result = num1 - num2;printf("结果: %.2f\n", result);break;case '*':result = num1 * num2;printf("结果: %.2f\n", result); break;case '/':if(num2 != 0)result = num1 / num2;printf("结果: %.2f\n", result); }elseprintf("除数不能为0!\n");}break;default:printf("无效的运算符!\n"); break;}return 0;```这个计算器程序可以接受两个数字和一个运算符作为输入,并根据运算符的类型进行相应的计算。
程序使用了`switch`语句来根据不同的运算符执行不同的操作。
输入数字之后,输出计算结果或者错误提示信息。
java计算器源代码Word文档
package计算器;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.math.BigDecimal;import javax.swing.BorderFactory;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;import javax.swing.border.BevelBorder;import javax.swing.text.BadLocationException;public class Counter1 extends JFrame implements ActionListener { public static final int DEF_DIV_SCALE = 10; //默认的精度private JMenuBar jmBar = new JMenuBar(); // 菜单条private JMenu edit = new JMenu("编辑(E)");private JMenu find = new JMenu("查看(V)");private JMenu help = new JMenu("帮助(H)");// 创建JPanel便于管理private JPanel panTxt = new JPanel();private JPanel panBack = new JPanel();private JPanel panMen = new JPanel();private JPanel panNum = new JPanel();// 创建文本域private JTextField txt = new JTextField();// 创建文本标签private JLabel jlm = new JLabel();private boolean flag = false; // 是否可以消除文本private double a = 0; // 数字a的值private double b = 0; // 数字b的值private double result = 0; // 两个数字运算的结果private String sign = ""; // 标记运算法则private double m = 0; // 暂时储存数据// 创建按钮private NewButton jbBack = new NewButton("Backspace", Color.RED);private NewButton jbCE = new NewButton("CE", Color.RED);private NewButton jbC = new NewButton("C", Color.RED);private NewButton jbMC = new NewButton("MC", Color.RED);private NewButton jbMR = new NewButton("MR", Color.RED);private NewButton jbMS = new NewButton("MS", Color.RED);private NewButton jbM = new NewButton("M+", Color.RED);public Counter1() {setSize(260, 260);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);setLayout(null);setJMenuBar(jmBar);setTitle("计算器");setResizable(false);init();// Container contentPane = getContentPane();// Controller c = new Controller(this);// contentPane.addKeyListener(c);}private void init() {// 设置第一个JPanel里面的内容panTxt.setSize(230, 20);panTxt.setLocation(15, 5);// panTxt.setBorder(BorderFactory.createLineBorder(Color.RED));panTxt.setLayout(new BorderLayout()); // 设置布局管理器txt.setHorizontalAlignment(JTextField.RIGHT); // 使光标定位在右边txt.setBorder(BorderFactory.createLoweredBevelBorder()); // 设置边框凹下去txt.setEditable(false); // 设置是否可以编辑txt.setBackground(Color.WHITE);// txt.setEnabled(true); //设置是否激活// txt.setFocusable(false); // 设置是否可以获得焦点(显示光标)txt.setText("0");add(panTxt);panTxt.add(txt);Controller c = new Controller(this);txt.addKeyListener(c);// 设置第二个JPanel里面的内容panBack.setSize(190, 25);panBack.setLocation(52, 35);// 画出边框便于查看// panBack.setBorder(BorderFactory.createLineBorder(Color.RED)); GridLayout layPanBack = new GridLayout(); // 创建布局管理器layPanBack.setHgap(5); // 设置布局管理器的边距panBack.setLayout(layPanBack); // 设置布局管理器// 添加按钮jbBack.setFont(new Font("宋体", 0, 12));panBack.add(jbBack);panBack.add(jbCE);panBack.add(jbC);add(panBack);// 设置第三个JPanel里面的内容panMen.setSize(40, 140);panMen.setLocation(5, 65);GridLayout layPanMen = new GridLayout(4, 1); // 创建布局管理器layPanMen.setVgap(5); // 设置布局管理器的边距panMen.setLayout(layPanMen);// panMen.setBorder(BorderFactory.createLineBorder(Color.RED)); panMen.add(jbMC);panMen.add(jbMR);panMen.add(jbMS);panMen.add(jbM);add(panMen);// 设置第四个JPanel里面的内容panNum.setSize(200, 140);panNum.setLocation(50, 65);// panNum.setBorder(BorderFactory.createLineBorder(Color.RED)); add(panNum);GridLayout layPanNum = new GridLayout(4, 5); // 创建布局管理器panNum.setLayout(layPanNum);newButtonNum();// 添加菜单项jmBar.add(edit);jmBar.add(find);jmBar.add(help);// 设置文本标签的属性和添加文本标签jlm.setBorder(BorderFactory.createBevelBorder(1));jlm.setSize(25, 25);jlm.setLocation(15, 35);add(jlm);}public void newButtonNum() {NewButton jb7 = new NewButton("7", Color.BLUE);NewButton jb8 = new NewButton("8", Color.BLUE);NewButton jb9 = new NewButton("9", Color.BLUE);NewButton jbDivide = new NewButton("/", Color.RED);NewButton jbSqrt = new NewButton("sqrt", Color.BLUE);NewButton jb4 = new NewButton("4", Color.BLUE);NewButton jb5 = new NewButton("5", Color.BLUE);NewButton jb6 = new NewButton("6", Color.BLUE);NewButton jbRide = new NewButton("*", Color.RED);NewButton jbPer = new NewButton("%", Color.BLUE);NewButton jb1 = new NewButton("1", Color.BLUE);NewButton jb2 = new NewButton("2", Color.BLUE);NewButton jb3 = new NewButton("3", Color.BLUE);NewButton jbCut = new NewButton("-", Color.RED);NewButton jbReciprocal = new NewButton("1/x", Color.BLUE);NewButton jb0 = new NewButton("0", Color.BLUE);NewButton jbMinus = new NewButton("+/-", Color.BLUE);NewButton jbDot = new NewButton(".", Color.BLUE);NewButton jbAdd = new NewButton("+", Color.RED);NewButton jbEquals = new NewButton("=", Color.RED);panNum.add(jb7);panNum.add(jb8);panNum.add(jb9);panNum.add(jbDivide);panNum.add(jbSqrt);panNum.add(jb4);panNum.add(jb5);panNum.add(jb6);panNum.add(jbRide);panNum.add(jbPer);panNum.add(jb1);panNum.add(jb2);panNum.add(jb3);panNum.add(jbCut);panNum.add(jbReciprocal);panNum.add(jb0);panNum.add(jbMinus);panNum.add(jbDot);panNum.add(jbAdd);panNum.add(jbEquals);}public static void main(String[] args) {try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 设置和win7的布局一样} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (UnsupportedLookAndFeelException e) {e.printStackTrace();}new Counter1().setVisible(true);}private class NewButton extends JButton {public NewButton(String s, Color c) {super(s);// setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));setBorder(BorderFactory.createEmptyBorder());setForeground(c);setFocusable(false); // 设置是否可以获得焦点(显示光标)addActionListener(Counter1.this);}}// 实现监听public void actionPerformed(ActionEvent e) {if (e.getActionCommand() == "+") {a = Double.parseDouble(txt.getText());sign = "+";flag = true;} else if (e.getActionCommand() == "-") {a = Double.parseDouble(txt.getText());sign = "-";flag = true;} else if (e.getActionCommand() == "*") {a = Double.parseDouble(txt.getText());sign = "*";flag = true;} else if (e.getActionCommand() == "/") {a = Double.parseDouble(txt.getText());sign = "/";flag = true;} else if (e.getActionCommand() == "=") {try {b = Double.parseDouble(txt.getText());} catch (NumberFormatException nfe) {b = 0;}try {if (sign == "+") {result = doubleAdd(a, b);} else if (sign == "-") {result = doubleSub(a, b);} else if (sign == "*") {result = doubleMul(a, b);} else if (sign == "/" && b != 0) {result = doubleDiv(a, b, 15);} else {result = b;}} catch (NumberFormatException nfe) {result = 0;}a = result;if (sign == "/" && b == 0) {txt.setText("0");} else {txt.setText(result + "");}flag = true;} else if (e.getActionCommand() == "C") {a = 0;result = 0;sign = "";txt.setText("0");} else if (e.getActionCommand() == "CE") {txt.setText("0");} else if (e.getActionCommand() == "Backspace") {try {if (txt.getText().length() > 1) {txt.setText(txt.getText(0, txt.getText().length() - 1));} else {txt.setText("0");}} catch (BadLocationException e1) {txt.setText("0");}} else if (e.getActionCommand() == "sqrt") {a = Double.parseDouble(txt.getText());result = Math.sqrt(a);a = result;txt.setText(result + "");flag = true;} else if (e.getActionCommand() == "%") {b = Double.parseDouble(txt.getText());result = doubleMul(doubleDiv(b, 100), a);txt.setText(result + "");flag = true;} else if (e.getActionCommand() == "1/x") {a = Double.parseDouble(txt.getText());result = 1 / a;a = result;txt.setText(result + "");flag = true;} else if (e.getActionCommand() == "+/-") {txt.setText("" + (-Double.parseDouble(txt.getText()))); } else if (e.getActionCommand() == "MC") {m = 0;jlm.setText("");} else if (e.getActionCommand() == "MR") {txt.setText(m + "");} else if (e.getActionCommand() == "MS") {m = Double.parseDouble(txt.getText());jlm.setText(" M");flag = true;} else if (e.getActionCommand() == "M+") {m += Double.parseDouble(txt.getText());flag = true;} else {boolean isDoc = false;for (int i = 0; i < txt.getText().length(); i++) { if (txt.getText().charAt(i) == '.') {isDoc = true;}}if (!isDoc || e.getActionCommand() != ".") {if (flag) {txt.setText("");flag = false;}if (txt.getText().equals("0") && e.getActionCommand() != ".") { txt.setText("");}txt.setText(txt.getText() + e.getActionCommand());}}}// 实现键盘监听public void keyAction(KeyEvent e) {if (e.getKeyChar() == '+') {a = Double.parseDouble(txt.getText());sign = "+";flag = true;} else if (e.getKeyChar() == '-') {a = Double.parseDouble(txt.getText());sign = "-";flag = true;} else if (e.getKeyChar() == '*') {a = Double.parseDouble(txt.getText());sign = "*";flag = true;} else if (e.getKeyChar() == '/') {a = Double.parseDouble(txt.getText());sign = "/";flag = true;} else if (e.getKeyChar() == '=') {try {b = Double.parseDouble(txt.getText());} catch (NumberFormatException nfe) {b = 0;}try {if (sign == "+") {result = doubleAdd(a, b);} else if (sign == "-") {result = doubleSub(a, b);} else if (sign == "*") {result = doubleMul(a, b);} else if (sign == "/") {if (b == 0) {txt.setText("除数不能为0");} else {result = doubleDiv(a, b, 15);}} else {result = b;}} catch (NumberFormatException nfe) {result = 0;}a = result;if (sign == "/" && b == 0) {txt.setText("0");} else {txt.setText(result + "");}flag = true;} else if (e.getKeyChar() == 'c' || e.getKeyChar() == 'C') {a = 0;result = 0;sign = "";txt.setText("0");} else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {try {if (txt.getText().length() > 1) {txt.setText(txt.getText(0, txt.getText().length() - 1));} else {txt.setText("0");}} catch (BadLocationException e1) {txt.setText("0");}} else if (e.getKeyChar() == '%') {b = Double.parseDouble(txt.getText());result = doubleMul(doubleDiv(b, 100), a);txt.setText(result + "");flag = true;} else {if (e.getKeyChar() >= 0x30 && e.getKeyChar() <= 0x39|| e.getKeyChar() == '.') {boolean isDoc = false;for (int i = 0; i < txt.getText().length(); i++) {if (txt.getText().charAt(i) == '.') {isDoc = true;}}if (!isDoc || e.getKeyChar() != '.') {if (flag) {txt.setText("");flag = false;}if (txt.getText().equals("0") && e.getKeyChar() != '.') {txt.setText("");}txt.setText(txt.getText() + e.getKeyChar());}}}}private class Controller extends KeyAdapter {private Counter1 frame;public Controller(Counter1 frame) {this.frame = frame;}public void keyPressed(KeyEvent e) {frame.keyAction(e);}}// 提供相对精确的加法运算public static double doubleAdd(double d1, double d2) {BigDecimal bd1 = new BigDecimal(Double.toString(d1));BigDecimal bd2 = new BigDecimal(Double.toString(d2));return bd1.add(bd2).doubleValue();}// 提供相对精确的减法运算public static double doubleSub(double d1, double d2) {BigDecimal bd1 = new BigDecimal(Double.toString(d1));BigDecimal bd2 = new BigDecimal(Double.toString(d2));return bd1.subtract(bd2).doubleValue();}// 提供相对精确的乘法运算public static double doubleMul(double d1, double d2) {BigDecimal bd1 = new BigDecimal(Double.toString(d1));BigDecimal bd2 = new BigDecimal(Double.toString(d2));return bd1.multiply(bd2).doubleValue();}// 提供相对精确的除法运算,当发生除不尽的情况时,精确到小数点以后10位,以后的数字四舍五入。
java简单计算器源代码Word版
简单计算器代码package calcultorthree;import java.awt.BorderLayout;//导入边界布局管理器类import java.awt.GridLayout;//导入网格布局管理器类import java.awt.TextField;//导入文本区域类import java.awt.event.ActionEvent;//导入事件类import java.awt.event.ActionListener;//导入事件监听者类import javax.swing.JButton;//导入按钮类import javax.swing.JFrame;//导入窗体import javax.swing.JPanel;//导入面板/***本例实现了简单计算器代码,具备加减乘除和正弦功能,旨在抱砖引玉。
熟悉java的同学,可以在此基础上实现更复杂的功能。
* @author Fjsh*/public class CalcultorThree {//新建对象,在构造函数中进行初始化JFrame frame;//新建窗体对象JButton buttonzero,buttondot,buttonequal;//新建按钮“0”“.”“=”JButton buttonplus,buttonminus,buttonmultiple,buttondevision,buttonsin,buttontozero;//新建按钮“+”“-”“*”“/”“sin”和归零按钮JButton buttonone,buttontwo,buttonthree,buttonfour,buttonfive,buttonsix,buttonseven,buttoneight,buttonnine;//新建数字按钮“0”“1”“2”“3”“4”“5”“6”“7”“8”“9”JPanel panelwest,panelcenter,paneleast;//新建三个面板TextField tf;//新建文本区域对象public CalcultorThree(){//初始化对象tf=new TextField(30);//构造空文本字段,字符宽度为30frame =new JFrame("CalculatorThree");//构造窗体对象,名称为“CalculatorThree”panelcenter=new JPanel();//构造面板,放到窗体中央panelwest=new JPanel();//构造面板,放到窗体西边paneleast=new JPanel();//构造面板,放到窗体东边Handle h=new Handle();//新建Handle类对象,Handle类为事件监听类//创建数字按钮对象,1、2、3、4、5、6、7、8、9buttonone=new JButton("1");buttontwo=new JButton("2");buttonthree=new JButton("3");buttonfour=new JButton("4");buttonfive=new JButton("5");buttonsix=new JButton("6");buttonseven=new JButton("7");buttoneight=new JButton("8");buttonnine=new JButton("9");panelcenter.setLayout(new GridLayout(3,3));//设置面板布局为网格布局,3行3列//将数字按钮添加到中间面板panelcenter.add(buttonone);panelcenter.add(buttontwo);panelcenter.add(buttonthree);panelcenter.add(buttonfour);panelcenter.add(buttonfive);panelcenter.add(buttonsix);panelcenter.add(buttonseven);panelcenter.add(buttoneight);panelcenter.add(buttonnine);//为10个按钮注册事件监听器buttonone.addActionListener(h);buttontwo.addActionListener(h);buttonthree.addActionListener(h);buttonfour.addActionListener(h);buttonfive.addActionListener(h);buttonsix.addActionListener(h);buttonseven.addActionListener(h);buttoneight.addActionListener(h);buttonnine.addActionListener(h);//构造按钮“0”“.”“=”,注册事件监听器,设置1行3列的布局,添加到到西边的面板buttonzero=new JButton("0");buttondot=new JButton(".");buttonequal=new JButton("=");buttonzero.addActionListener(h);buttondot.addActionListener(h);buttonequal.addActionListener(h);panelwest.setLayout(new GridLayout(3,1));panelwest.add(buttonzero);panelwest.add(buttondot);panelwest.add(buttonequal);//构造操作按钮“+”“-”“*”“/”“sin”“>0”,其中“>0”为归零按钮buttonplus=new JButton("+");buttonminus=new JButton("-");buttonmultiple=new JButton("*");buttondevision=new JButton("/");buttonsin=new JButton("sin");buttontozero=new JButton(">0");paneleast.setLayout(new GridLayout(3,1));//设置西边的布局为3行1列//将操作按钮“+”“-”“*”“/”“sin”“>0”添加到西边的面板中paneleast.add(buttonplus);paneleast.add(buttonminus);paneleast.add(buttonmultiple);paneleast.add(buttondevision);paneleast.add(buttonsin);paneleast.add(buttontozero);//为操作按钮“+”“-”“*”“/”“sin”“>0”注册监听器buttonplus.addActionListener(h);buttonminus.addActionListener(h);buttonmultiple.addActionListener(h);buttondevision.addActionListener(h);buttonsin.addActionListener(h);buttontozero.addActionListener(h);frame.setLayout(new BorderLayout());//设置窗体为边界布局frame.add(paneleast,"East");//将东边面板paneleast添加到窗体的东边frame.add(tf,BorderLayout.NORTH); //将tf文本区域添加到窗体的北边,即顶部frame.add(panelwest,BorderLayout.WEST);//将panelwest面板添加到窗体西边frame.add(panelcenter,BorderLayout.CENTER);//将panelcenter面板添加到窗体中间frame.pack();//设置窗体大小,适合其子组件的首选大小和布局frame.setLocation(500,500);//设置窗体显示位置为(500,500)frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置布局窗体默认关闭方式frame.setVisible(true);//设置窗体可见}public static void main(String[] args) {new CalcultorThree();//主方法中新建对象}class Handle implements ActionListener{//实现动作监听器类int biaozhi=0;//此标志标志加减乘除操作double flag1=0,flag2=0,flag3=0;//flag1、flag2为两个操作数,flag3为结果@Overridepublic void actionPerformed(ActionEvent e) { //方法重写try{//此处可能会产生异常,用try、catch捕捉异常,不用处理if(e.getSource()==buttondot){//小数点tf.setText("0.");}if(e.getSource()==buttontozero){//归零操作tf.setText("");}if(e.getSource()==buttonzero){//按键0操作tf.setText(tf.getText()+"0");flag1=Double.parseDouble(tf.getText());//将文本区域转换成Double类型,赋给flag1}if(e.getSource()==buttonone){//按键1操作tf.setText(tf.getText()+"1");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttontwo){//按键2操作tf.setText(tf.getText()+"2");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttonthree){//按键3操作tf.setText(tf.getText()+"3");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttonfour){//按键4操作tf.setText(tf.getText()+"4");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttonfive){//按键5操作tf.setText(tf.getText()+"5");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttonsix){//按键6操作tf.setText(tf.getText()+"6");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttonseven){//按键7操作tf.setText(tf.getText()+"7");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttoneight){//按键8操作tf.setText(tf.getText()+"8");flag1=Double.parseDouble(tf.getText());}else if(e.getSource()==buttonnine){//按键9操作tf.setText(tf.getText()+"9");flag1=Double.parseDouble(tf.getText());}if(e.getSource()==buttonplus){//加法操作tf.setText("");flag2=flag1;biaozhi=0;}if(e.getSource()==buttonminus){//减法操作tf.setText("");flag2=flag1;biaozhi=1;}if(e.getSource()==buttonmultiple){//乘法操作tf.setText("");flag2=flag1;biaozhi=2;}if(e.getSource()==buttondevision){//除法操作tf.setText("");flag2=flag1;biaozhi=3;}if(e.getSource()==buttonsin){//正弦操作flag3=Math.sin(flag1);tf.setText(flag3+"");}if(e.getSource()==buttonequal){//等号操作,利用biaozhi判断进行相应加减乘除操作if(biaozhi==0){flag3=flag1+flag2;}if(biaozhi==1){flag3=flag1-flag2;}if(biaozhi==2){flag3=flag1*flag2;}if(biaozhi==3){flag3=flag1/flag2;}tf.setText(flag3+"");}}catch(Exception ex){}}}}。
JAVA编写的计算器源代码(word文档良心出品)
package jsq;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.UIManager;public class Test implements ActionListener {/****/JFrame f = new JFrame();JTextField tf = new JTextField("0.");JMenuBar bar=new JMenuBar();JMenu menuEdit=new JMenu("编辑(E)");JMenu menuView=new JMenu("查看(V)");JMenu menuHelp=new JMenu("帮助(H)");JMenuItem menuEditCopy=new JMenuItem("复制(C)");JMenuItem menuEditPaste=new JMenuItem("粘贴(V)");JMenuItem menuHelpAbout = new JMenuItem("关于计算器(A)");JPanel panel0 = new JPanel();JPanel panel2 = new JPanel();JPanel panel = new JPanel();JPanel panel3 = new JPanel();JPanel panel4 = new JPanel();JPanel panel5 = new JPanel();JButton btBk = new JButton(" Backspace"); JButton btCe = new JButton("Ce");JButton btCl = new JButton("C");JButton bt7 = new JButton("7");JButton bt8 = new JButton("8");JButton bt9 = new JButton("9");JButton btDiv = new JButton("/");JButton btSqrt = new JButton("sqrt");JButton bt4 = new JButton("4");JButton bt5 = new JButton("5");JButton bt6 = new JButton("6");JButton btMult = new JButton("*"); JButton btMol = new JButton(" % ");JButton bt1 = new JButton("1");JButton bt2 = new JButton("2");JButton bt3 = new JButton("3");JButton btMinu = new JButton("-"); JButton btCoun = new JButton(" 1/x");JButton bt0 = new JButton("0");JButton btPoint = new JButton("."); JButton btEqual = new JButton("="); JButton btAdd = new JButton("+");JButton btSign = new JButton(" +/-");/***@param args*/public void init(){f.add(panel0);f.add(tf,"North");f.setJMenuBar(bar);bar.add(menuEdit);bar.add(menuView);bar.add(menuHelp);menuEdit.add(menuEditCopy);menuEdit.add(menuEditPaste);menuHelp.add(menuHelpAbout);tf.setEditable(false);//不可编辑tf.setHorizontalAlignment(JTextField.RIGHT);//从右侧输入数据panel0.add(panel2);panel0.add(panel);panel0.add(panel3);panel0.add(panel4);panel0.add(panel5);panel2.setLayout(new GridLayout(1,4));panel2.add(btBk);panel2.add(btCe);panel2.add(btCl);panel.setLayout(new GridLayout(1,5));panel.add(bt7);panel.add(bt8);panel.add(bt9);panel.add(btDiv);panel.add(btSqrt);//根号panel3.setLayout(new GridLayout(1,5));panel3.add(bt4);panel3.add(bt5);panel3.add(bt6);panel3.add(btMult);panel3.add(btMol);//百分号panel4.setLayout(new GridLayout(1,5));panel4.add(bt1);panel4.add(bt2);panel4.add(bt3);panel4.add(btMinu);panel4.add(btCoun);//倒数panel5.setLayout(new GridLayout(1,5));panel5.add(bt0);panel5.add(btPoint);panel5.add(btAdd);panel5.add(btEqual);panel5.add(btSign);//正负符号btBk.setForeground(new Color(255, 0, 0)); btCe.setForeground(new Color(255, 0, 0)); btCl.setForeground(new Color(255, 0, 0)); btAdd.setForeground(new Color(255, 0, 0)); btMult.setForeground(new Color(255, 0, 0)); btDiv.setForeground(new Color(255, 0, 0)); btMinu.setForeground(new Color(255, 0, 0)); btEqual.setForeground(new Color(255, 0, 0));bt0.setForeground(new Color(0,0,255));bt1.setForeground(new Color(0, 0, 255));bt2.setForeground(new Color(0,0,255));bt3.setForeground(new Color(0,0,255));bt4.setForeground(new Color(0,0,255));bt5.setForeground(new Color(0,0,255));bt6.setForeground(new Color(0,0,255));bt7.setForeground(new Color(0,0,255));bt8.setForeground(new Color(0,0,255));bt9.setForeground(new Color(0,0,255)); btSqrt.setForeground(new Color(0,0,255)); btMol.setForeground(new Color(0,0,255)); btCoun.setForeground(new Color(0,0,255)); btSign.setForeground(new Color(0,0,255));//注册监听bt1.addActionListener(this);bt2.addActionListener(this);bt3.addActionListener(this);bt4.addActionListener(this);bt5.addActionListener(this);bt6.addActionListener(this);bt7.addActionListener(this);bt8.addActionListener(this);bt9.addActionListener(this);bt0.addActionListener(this);btAdd.addActionListener(this);btMinu.addActionListener(this);btMult.addActionListener(this);btDiv.addActionListener(this);btEqual.addActionListener(this);btPoint.addActionListener(this);btSqrt.addActionListener(this);btMol.addActionListener(this);btCoun.addActionListener(this);btSign.addActionListener(this);btBk.addActionListener(this);btCe.addActionListener(this);btCl.addActionListener(this);menuEditCopy.addActionListener(this);menuEditPaste.addActionListener(this);menuHelpAbout.addActionListener(this);f.addWindowListener(new MyWinLis());f.setTitle("计算器");f.setSize(295,240);f.setResizable(false);//不能改变窗体大小f.setVisible(true);}String foreNum=null;String currOpr=null;String currNum=null;boolean i = true;String copy;//复制public void actionPerformed(ActionEvent e) {// TODO自动生成方法存根Object obj=e.getSource();//输入数字if(obj==bt1||obj==bt2||obj==bt3||obj==bt4||obj==bt5||obj==bt6||obj==bt7||obj== bt8||obj==bt9||obj==bt0){if(i==true)tf.setText(e.getActionCommand());elsetf.setText(tf.getText()+e.getActionCommand());i = false;}//小数点else if(obj==btPoint){if(i==false)tf.setText(tf.getText()+'.');}//实现开根号else if(obj==btSqrt){if(tf.getText().charAt(0)=='-'){tf.setText("函数输入无效");}elsetf.setText(Double.toString(ng.Math.sqrt(Double. parseDouble(tf.getText()))));i = true;}//实现倒数else if(obj==btCoun){if (tf.getText().charAt(0) == '0') {tf.setText("零不能求倒数");i = true;}else {String s = Double.toString(1 / Double.parseDouble(tf.getText()));foreNum = tf.getText();tf.setText(s);i = true;}}//实现+/-符号else if (obj == btSign) {boolean isNumber = true;String s = tf.getText();for (int m = 0; m< s.length(); m++)if (! (s.charAt(m) >= '0' && s.charAt(m) <='9' || s.charAt(m) =='.'||s.charAt(m) == '-')) {break;}if (isNumber == true) {//如果当前字符串首字母有-号,代表现在是个负数,再按下时,则将首符号去掉if (s.charAt(0) == '-') {tf.setText("");for (int m = 1; m< s.length(); m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);}}//如果当前字符串第一个字符不是符号,则添加一个符号在首字母处elsetf.setText('-' + s);}}//实现%功能else if(obj==btMol){boolean isNumber = true;if(isNumber==true)tf.setText(String.valueOf(Double.parseDouble(tf.getText())/100));elsetf.setText("错误");}//实现符号运算else if(obj==btAdd||obj==btMinu||obj==btDiv||obj==btMult){if(i==false){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currNum))) ;}}foreNum=tf.getText();tf.setText("");currOpr=e.getActionCommand();i = false;}//实现等号else if(obj==btEqual){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currN um)));}currOpr=e.getActionCommand();i = true;}//实现Backspace功能else if(obj==btBk){String s = tf.getText();tf.setText("");for (int m = 0;m <s.length() - 1; m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);i = true;}}//实现Ce功能else if (obj == btCe) {tf.setText("0.");}//实现C功能else if (obj == btCl) {foreNum=currNum="";tf.setText("0.");}//实现复制else if(obj==menuEditCopy){copy=tf.getText();}//实现粘贴else if (obj == menuEditPaste) {tf.setText(copy);}//实现帮助主题else if(obj == menuHelpAbout){ImageIcon icon = new ImageIcon("src//Icons//about1.jpg");JLabel label = new JLabel(icon);JOptionPane.showMessageDialog(f,label,"帮助主题",JOptionPane.PLAIN_MESSAGE);}}public static void main(String[] args) {// TODO自动生成方法存根try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//UIManager统一管理}catch(Exception e) {e.printStackTrace();}Test t = new Test();t.init();}}class MyWinLis implements WindowListener{public void windowActivated(WindowEvent arg0) {// TODO自动生成方法存根}public void windowClosed(WindowEvent arg0) { // TODO自动生成方法存根}public void windowClosing(WindowEvent arg0) { // TODO自动生成方法存根System.exit(0);}public void windowDeactivated(WindowEvent arg0) { // TODO自动生成方法存根}public void windowDeiconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowIconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowOpened(WindowEvent arg0) { // TODO自动生成方法存根}}。
java简易计算器源代码-5页word资料
package Swing;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Work1 {public static void main(String[] args) {new JsqView(340, 240);@SuppressWarnings("serial")class JsqView extends JFrame {JTextField jtf;JButton jb1, jb2, jb3;JButton[] jb;JPanel jp1, jp2, jp3, jp4;MyActionListener l;public JsqView(int weith, int heigh) {Container con = this.getContentPane();con.setLayout(new BorderLayout(5, 10));l = new MyActionListener(this);jtf = new JTextField(26);jp1 = new JPanel();jp1.add(jtf);jtf.setHorizontalAlignment(JTextField.RIGHT);jp3 = new JPanel();jp3.setLayout(new BorderLayout(5, 10));jb1 = new JButton("Backspace");jb2 = new JButton("CE");jb3 = new JButton("C");jb1.setForeground(Color.red);jb1.addActionListener(l);jb2.addActionListener(l);jb2.setForeground(Color.red);jb3.addActionListener(l);jb3.setForeground(Color.red);jp2 = new JPanel();jp2.setLayout(new GridLayout(1, 3, 5, 5));jp2.add(jb1);jp2.add(jb2);jp2.add(jb3);jp4 = new JPanel();jp4.setLayout(new GridLayout(4, 5, 5, 5));jb = new JButton[20];String[] str = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%","1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };for (int i = 0; i < 20; i++) {jb[i] = new JButton(str[i]);jb[i].addActionListener(l);if (i == 3 || i == 8 || i == 13 || i == 18 || i == 19) {jb[i].setForeground(Color.red);jp4.add(jb[i]);jp3.add(jp2, BorderLayout.NORTH);jp3.add(jp4);con.add(jp1, BorderLayout.NORTH);con.add(jp3);this.setTitle("计算器");this.setSize(weith, heigh);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);class MyActionListener implements ActionListener {JsqView jv;char operator;String temp;Count c = new Count();boolean b = false;public MyActionListener(JsqView jv) {this.jv = jv;public void actionPerformed(ActionEvent e) {String str = e.getActionCommand().trim();//System.out.println(str);if (str.matches("[\\d\\.]")) {//System.out.println(str);if(b){jv.jtf.setText("");b = false;StringBuffer sbf = new StringBuffer();String s = jv.jtf.getText().trim();sbf.append(s);if("".equals(s)&&".".equals(str)){sbf.append(0+str);}else if(s.matches("\\d+")){sbf.append(str);}else if(str.matches("\\d")){sbf.append(str);jv.jtf.setText(sbf.toString());} else if (str.matches("[\\+\\-\\*\\/\\%]")) {b =false;operator = str.charAt(0);//System.out.println(str);temp = jv.jtf.getText().trim();jv.jtf.setText("");} else if (str.equals("=")) {String s = jv.jtf.getText().trim();// System.out.println(temp);// System.out.println(s);if("".equals(s)||s==null||temp==null){return;if((temp.matches("\\d+\\.\\d+"))||(s.matches("\\d+\\.\\d+"))){double i = Double.parseDouble(temp);double j = Double.parseDouble(s);if(!b){temp=s;double sum =c.count(i, j, operator,jv);jv.jtf.setText(sum + "");}else{long i = Long.parseLong(temp);long j = Long.parseLong(s);if(!b){temp=s;long sum = c.count(i, j, operator,jv);jv.jtf.setText(sum + "");b = true;}else if(str.equals("1/x")){String s = jv.jtf.getText().trim();double i = Double.parseDouble(s);double sum = c.count(i,jv);jv.jtf.setText(sum + "");b = true;}else if(str.equals("CE")){b= false;jv.jtf.setText("");}else if(str.equals("Backspace")){b= false;jv.jtf.setText(temp);}else if(str.equals("sqrt")){b= true;String s = jv.jtf.getText().trim();double b = Math.sqrt(Double.parseDouble(s));jv.jtf.setText(b+"");}else if(str.equals("+/-")){String s = jv.jtf.getText().trim();if(s.startsWith("-")){s= s.substring(1, s.length());}else{s = "-"+s;jv.jtf.setText(s);class Count {public long count(long i,long j,char operator,JsqView jv){long num = 0;switch (operator) {case '+':num = i + j;break;case '-':num = i - j;break;case '*':num = i * j;break;case '/':if(j==0){try {throw new MyException();} catch (MyException e) {JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);return 0;num = i / j;break;case '%':num = i % j;break;default:break;return num;public double count(double i,double j,char operator,JsqView jv){double num = 0;switch (operator) {case '+':num = i + j;break;case '-':num = i - j;break;case '*':num = i * j;break;case '/':if(j==0.0){try {throw new MyException();} catch (MyException e) {JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);return 0;num = i / j;break;default:break;return num;public double count (double i,JsqView jv){double num;if(i==0.0){try {throw new MyException();} catch (MyException e) {JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);return 0;num = 1/i;return num;@SuppressWarnings("serial")class MyException extends Exception{public MyException(){super("除数不能为零");。
计算器(JAVA)源代码
//定义计算的类import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JTextField;public class Caculate implements ActionListener { //设置属性private String data;private JTextField text;private String result = "0";private boolean start_new = false;private double last_value = 0;private String ope = "";private double value = 0;public String getResult (){return result;}//定义一个构造方法public Caculate(JTextField text){this.text = text;}@Override//按钮事件处理public void actionPerformed(ActionEvent cal) { // TODO Auto-generated method stubdata = cal.getActionCommand();data = data.trim();if("0123456789".indexOf(data) != -1){numButton(data);}else if (".".indexOf(data) != -1){dotButton(data);}else if ("+-*/".indexOf(data) != -1){operateButton(data);}else if ("=".indexOf(data)!=-1){equalButton();}//System.out.println(data);System.out.println(result);text.setText(result);}//计算程序private void numButton(String da){if(!start_new){result = result + da;}else{result = da;}while (result.startsWith("0")&&!result.startsWith("0.")&&result.length()>0){ result = result.substring(1);}start_new = false;}private void dotButton(String da){if(da.indexOf(".")!= -1){result = result + da;}}private void operateButton(String da){if(result.length()>0){last_value = Double.parseDouble(result);ope = da;start_new = true;}}private void equalButton(){value = Double.parseDouble(result);if(ope.equals("+")){result = String.valueOf(last_value + value);}else if(ope.equals("-")){result = String.valueOf(last_value - value);}else if(ope.equals("*")){result = String.valueOf(last_value * value);}else if(ope.equals("/")){if(value == 0){result = "ERROR";}else{result = String.valueOf(last_value / value);}}// 去掉结尾的“.0000...”if (result.matches(".+\\.0+")) {result = result.substring(0, stIndexOf("."));}// 设置状态start_new = true;ope = "";}}import javax.swing.JTextField;public class Culator {private static final String String = null;JTextField op;private String re;/*** @param args*/public static void main(String[] args) {Culator cul = new Culator();cul.init();// TODO Auto-generated method stub}public void init(){javax.swing.JFrame frame = new javax.swing.JFrame(); frame.setTitle("计算器");java.awt.FlowLayout f1= new java.awt.FlowLayout();frame.setLayout(f1);javax.swing.JMenuBar cai = createMB();frame.setJMenuBar(cai);javax.swing.JButton mc = new javax.swing.JButton("MC");op= new javax.swing.JTextField("0",25);//设置数字从右边开始显示op.setHorizontalAlignment(JTextField.RIGHT);//设置按钮javax.swing.JButton mr = new javax.swing.JButton("MR"); javax.swing.JButton ms = new javax.swing.JButton("MS"); javax.swing.JButton mp = new javax.swing.JButton("M+"); javax.swing.JButton mm = new javax.swing.JButton("M-"); javax.swing.JButton delete = new javax.swing.JButton(" ←"); javax.swing.JButton ce = new javax.swing.JButton("CE "); javax.swing.JButton c = new javax.swing.JButton(" C "); javax.swing.JButton pm = new javax.swing.JButton(" ± "); javax.swing.JButton r = new javax.swing.JButton(" √"); javax.swing.JButton seven = new javax.swing.JButton(" 7 "); javax.swing.JButton eight = new javax.swing.JButton(" 8 "); javax.swing.JButton nine = new javax.swing.JButton(" 9 ");javax.swing.JButton under = new javax.swing.JButton(" / ");javax.swing.JButton percent = new javax.swing.JButton(" % ");javax.swing.JButton four = new javax.swing.JButton(" 4 ");javax.swing.JButton five = new javax.swing.JButton(" 5 ");javax.swing.JButton six = new javax.swing.JButton(" 6 ");javax.swing.JButton and = new javax.swing.JButton(" * ");javax.swing.JButton ds = new javax.swing.JButton("1/x");javax.swing.JButton one = new javax.swing.JButton(" 1 ");javax.swing.JButton two = new javax.swing.JButton(" 2 ");javax.swing.JButton three = new javax.swing.JButton(" 3 ");javax.swing.JButton m = new javax.swing.JButton(" - ");javax.swing.JButton equal = new javax.swing.JButton(" = ");javax.swing.JButton zero = new javax.swing.JButton(" 0 ");javax.swing.JButton dot = new javax.swing.JButton(" . ");javax.swing.JButton plus = new javax.swing.JButton(" + ");//添加按钮frame.add(op);frame.add(mc);frame.add(mr);frame.add(ms);frame.add(mp);frame.add(mm);frame.add(delete);frame.add(ce);frame.add(c);frame.add(pm);frame.add(r);frame.add(seven);frame.add(eight);frame.add(nine);frame.add(under);frame.add(percent);frame.add(four);frame.add(five);frame.add(six);frame.add(and);frame.add(ds);frame.add(one);frame.add(two);frame.add(three);frame.add(m);frame.add(equal);frame.add(zero);frame.add(dot);frame.add(plus);frame.setSize(290,300);//实例化一个Caculate类Caculate cal = new Caculate(op);//增加监听op.addActionListener(cal);mc.addActionListener(cal);mr.addActionListener(cal);ms.addActionListener(cal);mp.addActionListener(cal);mm.addActionListener(cal);delete.addActionListener(cal);ce.addActionListener(cal);c.addActionListener(cal);pm.addActionListener(cal);r.addActionListener(cal);seven.addActionListener(cal);eight.addActionListener(cal);nine.addActionListener(cal);under.addActionListener(cal); percent.addActionListener(cal);four.addActionListener(cal);five.addActionListener(cal);six.addActionListener(cal);and.addActionListener(cal);ds.addActionListener(cal);one.addActionListener(cal);two.addActionListener(cal);three.addActionListener(cal);m.addActionListener(cal);equal.addActionListener(cal);zero.addActionListener(cal);dot.addActionListener(cal);plus.addActionListener(cal);frame.setDefaultCloseOperation(3); frame.setResizable(false);frame.setVisible(true);}//创建一个设置TextField窗口容的函数//public void setOp(String re){// op.setText(re);//}//创建一个常带有菜单的菜单条,就加到JFrame上显示private javax.swing.JMenuBar createMB(){//创建菜单条javax.swing.JMenuBar mb = new javax.swing.JMenuBar();//创建查看菜单javax.swing.JMenu view = new javax.swing.JMenu("查看(V)");//创建菜单项javax.swing.JMenuItem biaozhun = new javax.swing.JMenuItem("标准型"); javax.swing.JMenuItem kexue = new javax.swing.JMenuItem("科学型"); javax.swing.JMenuItem chengxu = new javax.swing.JMenuItem("程序员"); javax.swing.JMenuItem tongji = new javax.swing.JMenuItem("统计信息"); javax.swing.JMenuItem history = new javax.swing.JMenuItem("历史");//将菜单项添加到菜单上view.add(biaozhun);view.add(kexue);view.add(chengxu);view.add(tongji);view.add(history);//创建编辑菜单javax.swing.JMenu operation = new javax.swing.JMenu("编辑(O)");//创建菜单项javax.swing.JMenuItem copy = new javax.swing.JMenuItem("复制"); javax.swing.JMenuItem paste = new javax.swing.JMenuItem("黏贴"); javax.swing.JMenuItem hr = new javax.swing.JMenuItem("历史记录");//将菜单项添加到菜单上operation.add(copy);operation.add(paste);operation.add(hr);//创建帮助菜单javax.swing.JMenu help = new javax.swing.JMenu("帮助(H)");//创建帮助菜单项javax.swing.JMenuItem vh = new javax.swing.JMenuItem("查看帮助"); javax.swing.JMenuItem about = new javax.swing.JMenuItem("关于计算器"); //将菜单项添加到菜单上help.add(vh);help.add(about);//加上一个分隔条help.addSeparator();//将菜单添加到菜单条上mb.add(view);mb.add(operation);mb.add(help);return mb;} }。
JAVA计算器内含源代码精品文档14页
XX学院计算机科学与技术系实验报告课程名称程序设计基础实验(2)实验项目应用系统的面向对象设计与分析实验类型综合性实验完成人所在班级指导教师完成日期2009年11月20日实验报告正文一.实验报告简表实验课题名称计算器综合性实验项目应用系统的面向对象设计与分析服务课程程序设计基础实验(2)实验小组组长指导教师参与实验人员及其在实验课题中承担的主要任务(包括组长)学号小组成员姓名班级在实验课题中的主要作用二、实验内容1、完成计算器的编写。
2、完成实验报告的写作.三、实验要求1、理解并掌握图形界面的设计。
2、理解整体算法的思路,即actionPerformed()的算法.3、进一步学习JAVA的编程思想。
四、实验目的1、理解并掌握图形界面的设计。
2、理解整体算法的思路,即actionPerformed()的算法。
3、通过设计成的计算器的按钮输入所需要计算的数字,根据自己所需进行加减乘除运算,得出结果。
4、进一步学习JAVA的编程思想。
五、实验条件编译器:NetBeansJava环境:JDK 6.0操作系统:Windows XP六、思路分析1.在开始写计算器之前,用笔在纸上画出计算器的草图,显示屏的位置,每个按钮的位置及大小比列。
2.使用setLayout(new GridLayout(6, 3, 10, 10));创建容器框框,使用JPanel JPanel pane = new JPanel();pane.setLayout(new BorderLayout());pane.add(result, BorderLayout.NORTH);pane.add(number_key, BorderLayout.SOUTH);通过之前的草图将按钮位置排好,这样计算器的外部形状也Ok。
3.图形边框解决了之后开始通过getSource()==“”去的事件源对象,进行实现按钮的输入;4.这是计算器最关键的一步——实现计算器的运算,首先定义四则运算的符号i 。
计算器的源代码
package class4;import javax.swing.*;import java.awt.event.*;import java.awt.GridLayout;publicclass Shixun extends JFrame implements ActionListener,ItemListener {JTextField jt = new JTextField(16) ;//计算器界面布置JButton b1 = new JButton("1") ;JButton b2 = new JButton("2") ;JButton b3 = new JButton("3") ;JButton b4 = new JButton("4") ;JButton b5 = new JButton("5") ;JButton b6 = new JButton("6") ;JButton b7 = new JButton("7") ;JButton b8 = new JButton("8") ;JButton b9 = new JButton("9") ;JButton b0 = new JButton("0") ;JButton b10 = new JButton ("/") ;JButton b11 = new JButton ("+") ;JButton b12 = new JButton ("-") ;JButton b13 = new JButton ("*") ;JButton b14 = new JButton ("=") ;JButton b15 = new JButton (".") ;JButton b16 = new JButton ("%") ;JButton b17 = new JButton ("c") ;JButton b18 = new JButton ("←") ;JButton b19 = new JButton ("√") ;/*JButton b20 = new JButton ("±") ;JButton b21 = new JButton ("(") ;JButton b22 = new JButton (")") ;JButton b23 = new JButton ("π") ;*/int index=0;boolean flag = true ;//第一次输入double sum = 0.0 ;//初始结果为0String str = "1234567890.*/+-%=√";Shixun(){setTitle ("计算器") ;setSize(210,205) ;setResizable(true) ;setVisible(true) ;setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;//设置关闭窗体GridLayout pl = new GridLayout(5,4,0,1) ;JPanel p = new JPanel () ;p.setLayout(pl) ;//将按钮组件添加到面板容器中p.add(b17) ;p.add(b18);p.add(b10);p.add(b13);p.add(b7) ;p.add(b8) ;p.add(b9) ;p.add(b12);p.add(b4) ;p.add(b5) ;p.add(b6) ;p.add(b11) ;p.add(b1) ;p.add(b2) ;p.add(b3) ;p.add(b16);p.add(b19);p.add(b0) ;p.add(b15) ;p.add(b14) ;/* p.add(b20);p.add(b21);p.add(b22);p.add(b23);*/add(p,"South");add(jt,"North");//设置监听器b0.addActionListener(this) ;b1.addActionListener(this) ;b2.addActionListener(this) ;b3.addActionListener(this) ;b4.addActionListener(this) ;b5.addActionListener(this) ;b6.addActionListener(this) ;b7.addActionListener(this) ;b8.addActionListener(this) ;b9.addActionListener(this) ;b10.addActionListener(this) ;b11.addActionListener(this) ;b12.addActionListener(this) ;b13.addActionListener(this) ;b14.addActionListener(this) ;b15.addActionListener(this) ;b16.addActionListener(this) ;b17.addActionListener(this) ;b18.addActionListener(this) ;b19.addActionListener(this) ; /* b20.addActionListener(this) ;b21.addActionListener(this) ;b22.addActionListener(this) ;b23.addActionListener(this) ;*/ }publicstaticvoid main(String[] args) {new Shixun() ;}publicvoid actionPerformed(ActionEvent e) {String s = e.getActionCommand() ;// String s1;if(s.equals("←")){String t = jt.getText() ;int l = t.length() ;t = t.substring(0, l-1) ;jt.setText(t) ;index=0;}elseif('0'<=s.charAt(0)&&s.charAt(0)<='9'|| e.getSource()==b15 ){ if(flag)jt.setText(s);elseif(e.getSource() == b15 ){index++;if(index>= 2){JOptionPane.showMessageDialog(null,"您的输入有误,请重新输入","系统消息:",RMATION_MESSAGE);jt.setText(jt.getText()) ;}else {jt.setText(jt.getText()+s) ;}}else {jt.setText(jt.getText()+s) ;index=0;}flag = false ;//非第一次输入}elseif(s.equals("c")){sum=0;jt.setText("") ;index=0;}else {double x = Double.parseDouble(jt.getText()) ;if(str.equals("+")) sum +=x;if(str.equals("-")) sum -=x;if(str.equals("/")) sum /=x;if(str.equals("*")) sum *=x;if(str.equals("=")) sum =x;if(str.equals("%")) sum %=x;if(str.equals("√")) sum =Math.sqrt(x) ;if(str.equals(".")) sum =x;jt.setText(""+sum) ;str = s ;flag=true ;}}@Overridepublicvoid itemStateChanged(ItemEvent e) { // TODO Auto-generated method stub}}。
(完整word版)用MATLAB实现计算器程序源代码(word文档良心出品)
function varargout = caculator(varargin)gui_Singleton = 1;gui_State = struct('gui_Name', mfilename, ...'gui_Singleton', gui_Singleton, ...'gui_OpeningFcn', @caculator_OpeningFcn, ...'gui_OutputFcn', @caculator_OutputFcn, ...'gui_LayoutFcn', [] , ...'gui_Callback', []);if nargin && ischar(varargin{1})gui_State.gui_Callback = str2func(varargin{1});endif nargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});elsegui_mainfcn(gui_State, varargin{:});endfunction caculator_OpeningFcn(hObject, eventdata, handles, varargin) handles.output = hObject;set(handles.edit1,'string','0');set(handles.edit5,'string','0');guidata(hObject, handles);function varargout = caculator_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output;function edit1_Callback(hObject, eventdata, handles)function edit1_CreateFcn(hObject, eventdata, handles)if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction edit2_Callback(hObject, eventdata, handles)function edit2_CreateFcn(hObject, eventdata, handles)if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction edit3_Callback(hObject, eventdata, handles)function edit3_CreateFcn(hObject, eventdata, handles)if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction pushbutton1_Callback(hObject, eventdata, handles)handles.num1=strcat(get(handles.edit1,'string'),'+');set(handles.edit1,'string',handles.num1);guidata(hObject,handles);function pushbutton2_Callback(hObject, eventdata, handles) handles.num2=strcat(get(handles.edit1,'string'),'-');set(handles.edit1,'string',handles.num2);guidata(hObject,handles);function pushbutton3_Callback(hObject, eventdata, handles) handles.num3=strcat(get(handles.edit1,'string'),'*');set(handles.edit1,'string',handles.num3);guidata(hObject,handles);function pushbutton4_Callback(hObject, eventdata, handles) handles.num4=strcat(get(handles.edit1,'string'),'/');set(handles.edit1,'string',handles.num4);guidata(hObject,handles);function pushbutton_1_Callback(hObject, eventdata, handles) handles.shu1=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu1=strcat(handles.yuanshu,handles.shu1);if length(handles.shu1)<2;elseif (length(handles.shu1)>=2)&&(handles.shu1(end-1)==')')&& (handles.shu1(1)=='l')temp=handles.shu1(end);handles.shu1(end)=handles.shu1(end-1);handles.shu1(end-1)=temp;endset(handles.edit1,'string',handles.shu1);guidata(hObject, handles);function pushbutton_2_Callback(hObject, eventdata, handles) handles.shu2=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu2=strcat(handles.yuanshu,handles.shu2);if length(handles.shu2)<2;elseif (length(handles.shu2)>=2)&&(handles.shu2(end-1)==')')&& (handles.shu2(1)=='l')temp=handles.shu2(end);handles.shu2(end)=handles.shu2(end-1);handles.shu2(end-1)=temp;endset(handles.edit1,'string',handles.shu2);guidata(hObject, handles);function pushbutton_4_Callback(hObject, eventdata, handles) handles.shu4=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu4=strcat(handles.yuanshu,handles.shu4);if length(handles.shu4)<2;elseif (length(handles.shu4)>=2)&&(handles.shu4(end-1)==')')&& (handles.shu4(1)=='l')temp=handles.shu4(end);handles.shu4(end)=handles.shu4(end-1);handles.shu4(end-1)=temp;endset(handles.edit1,'string',handles.shu4);guidata(hObject, handles);function pushbutton_3_Callback(hObject, eventdata, handles) handles.shu3=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu3=strcat(handles.yuanshu,handles.shu3);if length(handles.shu3)<2;elseif (length(handles.shu3)>=2)&&(handles.shu3(end-1)==')')&& (handles.shu3(1)=='l')temp=handles.shu3(end);handles.shu3(end)=handles.shu3(end-1);handles.shu3(end-1)=temp;endset(handles.edit1,'string',handles.shu3);guidata(hObject, handles);function pushbutton_5_Callback(hObject, eventdata, handles) handles.shu5=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu5=strcat(handles.yuanshu,handles.shu5);if length(handles.shu5)<2;elseif (length(handles.shu5)>=2)&&(handles.shu5(end-1)==')')&& (handles.shu5(1)=='l')temp=handles.shu5(end);handles.shu5(end)=handles.shu5(end-1);handles.shu5(end-1)=temp;endset(handles.edit1,'string',handles.shu5);guidata(hObject, handles);function pushbutton_9_Callback(hObject, eventdata, handles) handles.shu9=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu9=strcat(handles.yuanshu,handles.shu9);if length(handles.shu9)<2;elseif (length(handles.shu9)>=2)&&(handles.shu9(end-1)==')')&& (handles.shu9(1)=='l')temp=handles.shu9(end);handles.shu9(end)=handles.shu9(end-1);handles.shu9(end-1)=temp;endset(handles.edit1,'string',handles.shu9);guidata(hObject, handles);function pushbutton_7_Callback(hObject, eventdata, handles) handles.shu7=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu7=strcat(handles.yuanshu,handles.shu7);if length(handles.shu7)<2;elseif (length(handles.shu7)>=2)&&(handles.shu7(end-1)==')')&& (handles.shu7(1)=='l')temp=handles.shu7(end);handles.shu7(end)=handles.shu7(end-1);handles.shu7(end-1)=temp;endset(handles.edit1,'string',handles.shu7);guidata(hObject, handles);function pushbutton_8_Callback(hObject, eventdata, handles) handles.shu8=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu8=strcat(handles.yuanshu,handles.shu8);if length(handles.shu8)<2;elseif (length(handles.shu8)>=2)&&(handles.shu8(end-1)==')')&& (handles.shu8(1)=='l')temp=handles.shu8(end);handles.shu8(end)=handles.shu8(end-1);handles.shu8(end-1)=temp;endset(handles.edit1,'string',handles.shu8);guidata(hObject, handles);function pushbutton_6_Callback(hObject, eventdata, handles) handles.shu6=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu6=strcat(handles.yuanshu,handles.shu6);if length(handles.shu6)<2;elseif (length(handles.shu6)>=2)&&(handles.shu6(end-1)==')')&& (handles.shu6(1)=='l')temp=handles.shu6(end);handles.shu6(end)=handles.shu6(end-1);handles.shu6(end-1)=temp;endset(handles.edit1,'string',handles.shu6);guidata(hObject, handles);function pushbutton18_Callback(hObject, eventdata, handles) handles.jieguo=get(handles.edit1,'string');handles.jieguo=strcat('=',handles.jieguo);eval(['handles.result''1' handles.jieguo]);set(handles.edit5,'string',num2str(handles.result1));guidata(hObject,handles);function pushbutton_0_Callback(hObject, eventdata, handles) handles.shu0=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');if handles.yuanshu(end)=='N';handles.yuanshu(end)='';endif handles.yuanshu(1)=='0';handles.yuanshu=handles.yuanshu(2:end);endhandles.shu0=strcat(handles.yuanshu,handles.shu0);if length(handles.shu0)<2;elseif (length(handles.shu0)>=2)&&(handles.shu0(end-1)==')')&& (handles.shu0(1)=='l')temp=handles.shu0(end);handles.shu0(end)=handles.shu0(end-1);handles.shu0(end-1)=temp;endset(handles.edit1,'string',handles.shu0);guidata(hObject, handles);function pushbutton20_Callback(hObject, eventdata, handles) handles.shu10=get(hObject,'string');handles.yuanshu=get(handles.edit1,'string');handles.shu10=strcat(handles.yuanshu,handles.shu10);set(handles.edit1,'string',handles.shu10);guidata(hObject, handles);function pushbutton21_Callback(hObject, eventdata, handles) function edit5_Callback(hObject, eventdata, handles)function edit5_CreateFcn(hObject, eventdata, handles)if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction pushbutton22_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.fanhao=strcat('-(',handles.yuanshu,')');set(handles.edit1,'string',handles.fanhao);guidata(hObject, handles);function pushbutton23_Callback(hObject, eventdata, handles)set(handles.edit1,'string','0');set(handles.edit5,'string','0');guidata(hObject, handles);function pushbutton24_Callback(hObject, eventdata, handles)result=questdlg('ÕæµÄÒªÍ˳ö£¿','Í˳öÈ·ÈÏ','È·¶¨','È¡Ïû','È¡Ïû'); if result=='È·¶¨', close(gcf); endfunction pushbutton25_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.sin=strcat('sin(',handles.yuanshu,')');set(handles.edit1,'string',handles.sin);guidata(hObject, handles);function pushbutton26_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.cos=strcat('cos(',handles.yuanshu,')');set(handles.edit1,'string',handles.cos);guidata(hObject, handles);function pushbutton27_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.tan=strcat('tan(',handles.yuanshu,')');set(handles.edit1,'string',handles.tan);guidata(hObject, handles);function pushbutton28_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.ln=strcat('reallog(',handles.yuanshu,')');set(handles.edit1,'string',handles.ln);guidata(hObject, handles);function pushbutton29_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.log=strcat('log',handles.yuanshu,'()');set(handles.edit1,'string',handles.log);guidata(hObject, handles);function pushbutton30_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.daoshu=strcat('1/(',handles.yuanshu,')');set(handles.edit1,'string',handles.daoshu);guidata(hObject, handles);function pushbutton31_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.sqrt=strcat('sqrt(',handles.yuanshu,')');set(handles.edit1,'string',handles.sqrt);guidata(hObject, handles);function pushbutton32_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.pingfang=strcat('(',handles.yuanshu,')^2');set(handles.edit1,'string',handles.pingfang);guidata(hObject, handles);function pushbutton33_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.ncifang=strcat('(',handles.yuanshu,')^N');set(handles.edit1,'string',handles.ncifang);guidata(hObject, handles);function pushbutton35_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.kuohao=strcat('(',handles.yuanshu,')');set(handles.edit1,'string',handles.kuohao);guidata(hObject, handles);function pushbutton36_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.yuanshu=handles.yuanshu(1:(end-1));if length(handles.yuanshu)<1handles.yuanshu='0';endset(handles.edit1,'string',handles.yuanshu);guidata(hObject, handles);% --- Executes on button press in pushbutton37.function pushbutton37_Callback(hObject, eventdata, handles) handles.yuanshu=get(handles.edit1,'string');handles.exp=strcat('exp(',handles.yuanshu,')');set(handles.edit1,'string',handles.exp);guidata(hObject, handles);% --- Executes when user attempts to close figure1.function figure1_CloseRequestFcn(hObject, eventdata, handles)% hObject handle to figure1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)% Hint: delete(hObject) closes the figuredelete(hObject);%--------------------------------------------------------------------function Untitled_14_Callback(hObject, eventdata, handles)% hObject handle to Untitled_14 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)%--------------------------------------------------------------------function Untitled_15_Callback(hObject, eventdata, handles)set(gcf,'color','red')% hObject handle to Untitled_15 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)%--------------------------------------------------------------------function Untitled_16_Callback(hObject, eventdata, handles)set(gcf,'color','blue')% hObject handle to Untitled_16 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)%--------------------------------------------------------------------function Untitled_17_Callback(hObject, eventdata, handles)set(gcf,'color','green')% hObject handle to Untitled_17 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)%--------------------------------------------------------------------function Untitled_18_Callback(hObject, eventdata, handles)set(gcf,'color','black')% hObject handle to Untitled_18 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)%--------------------------------------------------------------------function Untitled_19_Callback(hObject, eventdata, handles)set(gcf,'color','yellow')% hObject handle to Untitled_19 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)%--------------------------------------------------------------------function Untitled_20_Callback(hObject, eventdata, handles)set(gcf,'color','m')% hObject handle to Untitled_20 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function Untitled_1_Callback(hObject, eventdata, handles)function Untitled_2_Callback(hObject, eventdata, handles)function Untitled_3_Callback(hObject, eventdata, handles)function Untitled_4_Callback(hObject, eventdata, handles)function Untitled_4_CreateFcn(hObject, eventdata, handles)function Untitled_5_Callback(hObject, eventdata, handles)function Untitled_6_Callback(hObject, eventdata, handles)。
计算器源代码
package cn.mycalculator;import java.awt.*;import java.util.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;import java.io.*;import java.text.*;public class MyCalculator implements ActionListener {static JDialog login, addUser; //登入和注册对话框static String front = "", behind = ""; //分别用于记录加减乘除运算符之前,之后输入的内容static String op; //用于记录运算符static String re; //用于存储运算结果的字符串格式static String sdata; //用于存储计算数据的字符串格式static boolean flag = false; //用于记录是否按下了运算符static boolean flag1 = false;//用于判断是否输入了点运算符static double result; //用于存储运算结果static boolean flag2 = false;//用于判断是否输入了数字static boolean flag3 = false;//用于判断是否按下了等号运算符static boolean flag4 = false; //用于判断上次运算是否结束JFrame frame;JTextField textf;JPanel panel1,panel2,panel3,pan1,pan2,pan3,pan4;JButton b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,badd,bsub,bmul,bdiv,bpoint,brecip,bsin,bcos,btan,bbackspace,bclear,bequal,bconvert;public MyCalculator() {try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch (Exception e) {System.out.println ( "无法设置界面风格");}frame = new JFrame("计算器");//创建窗口frame.setSize(400,400);frame.setLayout(new BorderLayout(3,3));frame.setLocation(150,100);JMenuBar mBar = new JMenuBar(); //创建菜单条对象JMenu mView= new JMenu("查看(V)"); //创建查看菜单JMenuItem mRecord=new JMenuItem("历史纪录(H)"); //创建历史记录菜单项JMenuItem uInform=new JMenuItem("用户信息(U)"); //创建用户信息菜单项textf=new JTextField();textf.setHorizontalAlignment(JTextField.RIGHT);//从右往左输入textf.setEnabled(false);//关闭文本框,文本框不能输入字符textf.setFont(new java.awt.Font("Dialog", Font.PLAIN, 20));textf.setEditable(false);//是文本框中的字符处于不能编辑状态panel1= new JPanel();panel2= new JPanel();panel3= new JPanel();pan1= new JPanel();pan2= new JPanel();pan3= new JPanel();pan4= new JPanel();pan1.setLayout(new GridLayout(1,2,3,3));bbackspace=new JButton("←");bbackspace.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); bbackspace.setBackground(new Color(0,255,255));bclear=new JButton("C");bclear.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));bclear.setBackground(new Color(0,255,255));pan1.add(bbackspace);pan1.add(bclear);pan2.setLayout(new GridLayout(4,3,3,3));b7=new JButton("7"); //创建计算器界面按钮b7.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b7.setBackground(new Color(83,99,114));b8=new JButton("8");b8.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b8.setBackground(new Color(83,99,114));b9=new JButton("9");b9.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b9.setBackground(new Color(83,99,114));b4=new JButton("4");b4.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b4.setBackground(new Color(83,99,114));b5=new JButton("5");b5.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b5.setBackground(new Color(83,99,114));b6=new JButton("6");b6.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b6.setBackground(new Color(83,99,114));b1=new JButton("1");b1.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b1.setBackground(new Color(83,99,114));b2=new JButton("2");b2.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b2.setBackground(new Color(83,99,114));b3=new JButton("3");b3.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b3.setBackground(new Color(83,99,114));pan2.add(b1); pan2.add(b2); pan2.add(b3);pan2.add(b4); pan2.add(b5); pan2.add(b6);pan2.add(b7); pan2.add(b8); pan2.add(b9);b0=new JButton("0");b0.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));b0.setBackground(new Color(83,99,114));bpoint=new JButton(".");bpoint.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); bpoint.setBackground(new Color(83,99,114));bconvert=new JButton("+/-");bconvert.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); bconvert.setBackground(new Color(83,99,114));pan2.add(b0); pan2.add(bpoint); pan2.add(bconvert);pan3.setLayout(new GridLayout(4,2,3,3));badd=new JButton("+");badd.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); badd.setBackground(new Color(160,97,38));bsub=new JButton("-");bsub.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); bsub.setBackground(new Color(160,97,38));bmul=new JButton("×");bmul.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));bmul.setBackground(new Color(160,97,38));bdiv=new JButton("÷");bdiv.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));bdiv.setBackground(new Color(160,97,38));bsin=new JButton("sin");bsin.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));bsin.setBackground(new Color(160,97,38));bcos=new JButton("cos");bcos.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); bcos.setBackground(new Color(160,97,38));btan=new JButton("tan");btan.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); btan.setBackground(new Color(160,97,38));brecip=new JButton("1/x");brecip.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); brecip.setBackground(new Color(160,97,38));pan3.add(badd); pan3.add(bsin); pan3.add(bsub);pan3.add(bcos); pan3.add(bmul); pan3.add(btan);pan3.add(bdiv); pan3.add(brecip);pan4.setLayout(new GridLayout(1,1,1,1));bequal=new JButton("=");bequal.setFont(new java.awt.Font("Dialog", Font.BOLD, 15)); bequal.setBackground(new Color(255,0,0));pan4.add(bequal);mView.add(mRecord); //在查看菜单里面添加历史记录菜单项mView.add(uInform); //在查看菜单里面添加用户信息菜单项mBar.add(mView); //在菜单条上添加查看菜单frame.setJMenuBar(mBar); //在窗体上添加菜单条textf.setText("0");frame.add(textf,BorderLayout.NORTH);frame.add(panel1,BorderLayout.CENTER);panel1.add(panel2);panel1.add(panel3);panel2.setLayout(new BorderLayout(5,5));panel3.setLayout(new BorderLayout(5,5));panel2.add(pan1,BorderLayout.NORTH);panel2.add(pan2,BorderLayout.CENTER);panel3.add(pan3,BorderLayout.CENTER);panel3.add(pan4,BorderLayout.SOUTH);mRecord.addActionListener(this);//为各个按钮添加监听器功能uInform.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);b0.addActionListener(this);bpoint.addActionListener(this);bconvert.addActionListener(this);badd.addActionListener(this);bsub.addActionListener(this);bmul.addActionListener(this);bdiv.addActionListener(this);bsin.addActionListener(this);bcos.addActionListener(this);btan.addActionListener(this);brecip.addActionListener(this);bbackspace.addActionListener(this);bclear.addActionListener(this);bequal.addActionListener(this);loginDialog(); //启动登入界面}public void actionPerformed(ActionEvent e)//对每个每个按钮做出响应{if (e.getActionCommand().equals("历史纪录(H)"))showRecord();if (e.getActionCommand().equals("用户信息(U)"))showUseInform();if(e.getSource()==b0)pressNumber(e);else if(e.getSource()==b1)pressNumber(e);else if(e.getSource()==b2)pressNumber(e);else if(e.getSource()==b3)pressNumber(e);else if(e.getSource()==b4)pressNumber(e);else if(e.getSource()==b5)pressNumber(e);else if(e.getSource()==b6)pressNumber(e);else if(e.getSource()==b7)pressNumber(e);else if(e.getSource()==b8)pressNumber(e);else if(e.getSource()==b9)pressNumber(e);else if(e.getSource()==bpoint) pressPoint(e);else if(e.getSource()==badd)pressArithmetic(e);else if(e.getSource()==bsub)pressArithmetic(e);else if(e.getSource()==bmul)pressArithmetic(e);else if(e.getSource()==bdiv)pressArithmetic(e);else if(e.getSource()==bsin){pressTriangular(e);flag4 = true;flag = false;}else if(e.getSource()==bcos){pressTriangular(e);flag4 = true;flag = false;}else if(e.getSource()==btan){pressTriangular(e);flag4 = true;flag = false;}else if(e.getSource()==bconvert) pressConvert(e);else if (e.getSource()==brecip){ pressRecip(e);flag4 = true;flag = false;}else if (e.getSource()==bbackspace)pressBackspace(e);else if (e.getSource()==bclear)pressClear(e);else if(e.getSource()==bequal){pressEqual(e);flag4 = true;}}public void pressNumber(ActionEvent e)//对按0作出反应{if(flag4&&!flag){//判断上次运算是否结束,如果结束则重新输入数字进行下次运算textf.setText("");if (flag1) {//判断之前是否输入了点运算符textf.setText("0." + e.getActionCommand());flag1 = false;} else {textf.setText(e.getActionCommand());}front="";flag4=false;flag2=false;}else if (flag) { //如果刚刚按下了运算符textf.setText("");if (flag1) {//判断之前是否输入了点运算符textf.setText("0." + e.getActionCommand());flag1 = false;} else {textf.setText(e.getActionCommand());}flag2 = true;} else if(!flag4){int num = textf.getText().indexOf(".");if (num < 0 && !textf.getText().equals("0")) {textf.setText(textf.getText() + e.getActionCommand());} else if (num < 0 && textf.getText().equals("0")) {textf.setText(e.getActionCommand());} else if (num >= 0 && textf.getText().equals("0")) {textf.setText("0." + e.getActionCommand());} else if (num >= 0 && !textf.getText().equals("0")) {textf.setText(textf.getText() + e.getActionCommand());}}flag = false;flag3=false;}public void pressPoint(ActionEvent e) { //点运算符事件处理int num=textf.getText().indexOf(".");if(num<0 && !flag)textf.setText(textf.getText()+e.getActionCommand());if(flag)flag1=true;}public void pressArithmetic(ActionEvent e) { //加,减,乘,除运算符事件处理if(flag3){textf.setText(textf.getText());op = e.getActionCommand(); //得到刚刚按下的运算符front = textf.getText(); //记录加减乘除运算符之前输入的内容}else if (flag2) {ActionEvent ee = new ActionEvent("qq", 1, "pp");pressEqual(ee);op = e.getActionCommand(); //得到刚刚按下的运算符front = re;flag2 = false;} else {front = textf.getText(); //记录加减乘除运算符之前输入的内容op = e.getActionCommand(); //得到刚刚按下的运算符}flag3=false;flag = true; //记录已经按下了加减乘除运算符的其中一个if(flag4)flag4=false;}public void pressTriangular(ActionEvent e){ //三角函数运算符事件处理front = textf.getText();Double number = Double.parseDouble(front);op=e.getActionCommand();switch(op){case "sin":result = Math.sin(number*Math.PI/180.0);re = Double.toString(result);textf.setText(re);sdata = "sin"+textf.getText()+"="+re;save(sdata); //保存运算信息sdata = null;break;case "cos":result = Math.cos(number*Math.PI/180.0);re = Double.toString(result);textf.setText(re);sdata = "cos" + textf.getText() + "=" + re;save(sdata);sdata = null;break;case "tan":if(number==90||number==-90||number==270||number==-270) re = "无穷大";else {result = Math.tan(number*Math.PI/180.0);re = Double.toString(result);}textf.setText(re);sdata = "tan" + textf.getText() + "=" + re;save(sdata);sdata = null;break;}}public void pressConvert(ActionEvent e) { //取反运算符事件处理if(textf.getText().equals("0")){ //如果文本框内容为0textf.setText(textf.getText());}else if(textf.getText().indexOf("-")>=0){//若文本框中含有负号String a=textf.getText().replaceAll("-","");textf.setText(a);}else if(flag){textf.setText("0");}else{textf.setText("-"+textf.getText());}}public void pressRecip(ActionEvent e) { //倒数运算符事件处理front = textf.getText();Double number = Double.parseDouble(front);if(number!=0){result=1/number;re = Double.toString(result);sdata = textf.getText() + "的倒数= " + re;save(sdata);sdata = null;}else{re="0不能求倒数";sdata = re;save(sdata);sdata = null;}textf.setText(re);}public void pressClear(ActionEvent e) { //清零运算符事件处理flag=false;flag1=false;flag2=false;flag3=false;front="";behind="";re="";textf.setText("0");}public void pressBackspace(ActionEvent e) { //退格事件处理String str=textf.getText();if(str.length() == 1){//如文本框中只剩下最后一个字符,将文本框内容置为0 textf.setText("0");}if(str.length()>1){str=str.substring(0,str.length()-1);textf.setText(str);}}public void pressEqual(ActionEvent e) { //等号的事件处理if(!flag3)//未曾按下等于运算符behind = textf.getText();elsefront = re;try {double a1 = Double.parseDouble(front);double b1 = Double.parseDouble(behind);if (op == "+") {result = a1 + b1;sdata = front + "+" + behind + "=" + Double.toString(result);save(sdata);sdata = null;} else if (op == "-") {result = a1 - b1;sdata = front + "-" + behind + "=" + Double.toString(result);save(sdata);sdata = null;} else if (op == "×") {result = a1 * b1;sdata = front + "*" + behind + "=" + Double.toString(result);save(sdata);sdata = null;} else {result = a1 / b1;if(b1!=0){sdata = front + "*" + behind + "=" + Double.toString(result);save(sdata);sdata = null;}}re = Double.toString(result);textf.setText(re);} catch (ArithmeticException ce) {textf.setText("除数不能为零");}if (!flag3)flag3 = true;}private void showRecord() { //显示数据记录窗口JDialog dialog = new JDialog(frame, "历史记录", true);JTextArea area = new JTextArea();area.setEditable(false);dialog.add(new JScrollPane(area));dialog.setSize(640, 480);dialog.setLocationRelativeTo(null);try {File file = new File("data.txt");if (!file.exists())file.createNewFile();char[] ch = new char[(int)file.length()];FileReader in = new FileReader(file);in.close();area.setText(new String(ch));} catch(IOException e) {e.printStackTrace();}dialog.setVisible(true);}private void showUseInform(){JDialog dialog = new JDialog(frame, "用户信息", true);JTextArea area = new JTextArea();area.setEditable(false);dialog.add(new JScrollPane(area));dialog.setSize(640, 480);dialog.setLocationRelativeTo(null);try {File file = new File("user.dat");if (!file.exists()) file.createNewFile();char[] ch = new char[(int)file.length()];FileReader in = new FileReader(file);in.read(ch);in.close();area.setText(new String(ch));} catch(IOException e) {e.printStackTrace();}dialog.setVisible(true);}/**************************登陆注册界面*****************************/ public void loginDialog() {login = new JDialog();login.setTitle("登录");login.setLayout(new FlowLayout());login.getContentPane().setBackground(new Color(170,212,255));login.add(new JLabel("用户名:"));final JTextField name = new JTextField(15);login.add(name);login.add(new JLabel("密码:"));final JPasswordField password = new JPasswordField(15);password.setEchoChar('*');JButton confirm = new JButton("登录");confirm.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (compareUserData(name.getText().trim(), new String(password.getPassword()))){login.setVisible(false);frame.pack();frame.setVisible(true);}else {JOptionPane.showMessageDialog(login, "用户名或密码错误!", "错误提示",JOptionPane.ERROR_MESSAGE);}}});login.add(confirm); //添加登入按钮final JDialog regDialog = new JDialog(login, "注册", true);registerDialog(regDialog);JButton register = new JButton("注册");register.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {login.setVisible(false);regDialog.setVisible(true);}});login.add(register);login.setSize(350, 150);login.setResizable(false);login.setLocationRelativeTo(null);login.setVisible(true);}/********************用户名密码的确认*******************************/ private boolean compareUserData(String name, String password) {try {RandomAccessFile out = new RandomAccessFile("user.dat", "rw");String fname, fpassword = null;while (out.getFilePointer() < out.length()) {fname = out.readUTF();out.readUTF();fpassword = out.readUTF();if (fname.equals(name)&&fpassword.equals(password))return true;}out.close();} catch (IOException e) {e.printStackTrace();}return false;}/**************************注册用户的信息************************************/ private void registerDialog(final JDialog regDialog) {Box box1 = Box.createVerticalBox();box1.add(new JLabel("用户名:", JLabel.RIGHT));box1.add(Box.createVerticalStrut(10));box1.add(new JLabel("性别:", JLabel.RIGHT));box1.add(Box.createVerticalStrut(10));box1.add(new JLabel("密码:", JLabel.RIGHT), -1);box1.add(Box.createVerticalStrut(10));box1.add(new JLabel("确认密码:", JLabel.RIGHT));Box box2 = Box.createVerticalBox();final JTextField nameTextField = new JTextField(10);box2.add(nameTextField);box2.add(Box.createVerticalStrut(8));final CheckboxGroup cbg = new CheckboxGroup();Box box21 = Box.createHorizontalBox();final Checkbox cb1 = new Checkbox("男", cbg, true);box21.add(cb1);box21.add(new Checkbox("女", cbg, false));box2.add(box21);box2.add(Box.createVerticalStrut(8));final JPasswordField pass1 = new JPasswordField(10);box2.add(pass1);box2.add(Box.createVerticalStrut(8));final JPasswordField pass2 = new JPasswordField(10);box2.add(pass2);Box baseBox = Box.createHorizontalBox();baseBox.add(box1);baseBox.add(box2);regDialog.setLayout(new FlowLayout());regDialog.add(baseBox);JButton confirm = new JButton("确定");JButton cancel = new JButton("取消");regDialog.add(confirm);regDialog.add(cancel);regDialog.setSize(150, 200);regDialog.setResizable(false);regDialog.setLocationRelativeTo(null);confirm.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {String sex = null;if (cbg.getSelectedCheckbox() == cb1)sex = "Sex:Boy";elsesex = "Sex:Girl";if (saveUserData(nameTextField.getText().trim(), sex,new String(pass1.getPassword()), new String(pass2.getPassword()))){regDialog.setVisible(false);login.setVisible(true);}elseJOptionPane.showMessageDialog(regDialog, "输入有误,请检查", "错误提示",JOptionPane.ERROR_MESSAGE);}});cancel.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {{regDialog.setVisible(false);login.setVisible(true);}}});}/********************************用户信息的储存***************************/ private boolean saveUserData(String name, String sex, String password1, String password2) {if (!password1.equals(password2))return false;try {RandomAccessFile out = new RandomAccessFile("user.dat", "rw");out.seek(out.length());out.writeUTF(name);out.writeUTF(sex);out.writeUTF(password1);out.close();} catch (IOException e) {e.printStackTrace();return false;}return true;}private void save(String s) {final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss: ");String time = sdf.format(new Date(System.currentTimeMillis()));try {File file = new File("data.txt");if (!file.exists()) file.createNewFile();char[] ch = new char[(int)file.length()];FileReader in = new FileReader(file);in.read(ch);in.close();FileWriter out = new FileWriter(file);String tmp = new String(ch);out.write(tmp.trim() + System.getProperty("line.separator"));out.write((time + s).trim() + System.getProperty("line.separator"));out.close();}catch(IOException e) {e.printStackTrace();}}public static void main(String[] args){new MyCalculator();}}。
科学计算器源代码
科学计算器源代码以下是一个简单的科学计算器的源代码,包含了基本的数学运算、三角函数、指数和对数运算、阶乘和组合运算等功能。
```#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;```这个科学计算器的源代码使用了面向对象的编程思想,将不同的数学运算封装成类的成员函数。
计算器源代码
#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语⾔计算器程序源代码//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;}}//主循环结束}//主函数结束。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
头文件class CCacl2Dlg : public CDialog{// Constructionpublic:int m_fun; //m_fun是运算符如:+,-,*,/void AddFun(int j); //该函数的功能是输入数字void AddNum(int i); //该函数的功能是输入运算符int m_ForS; //指示此时输入的是//第一个数还是第二个数bool m_firx,m_secx; //指示此时是否在输入小数部分//即是否按过了小数点double m_first,m_second; //第一第二个数double m_firstz,m_secondz; //第一第二个数的整数部分double m_firstx,m_secondx; //第一第二个数的小数部分int m_firxw,m_secxw; //第一第二个数的小数部分的位数int m_firzorf,m_seczorf; //指示是否是负数//既是否按过+/-键bool m_EnterSec; //是否输入了第二个数;double m_result; //结果double m_mfir,m_msec; // 记住上次参加运算的第一二个数bool m_sfmf,m_sfms,m_sfmfun; //指示是否此时还记的上次的数和运算符 int m_mfun; //记住上次的运算符CCacl2Dlg(CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CCacl2Dlg)enum { IDD = IDD_CACL2_DIALOG };CEdit m_xedit;double m_x;//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CCacl2Dlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CCacl2Dlg)afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void On0();afx_msg void On1();afx_msg void On2();afx_msg void On3();afx_msg void On4();afx_msg void On5();afx_msg void On6();afx_msg void On7();afx_msg void On8();afx_msg void On9();afx_msg void OnAdd();afx_msg void OnBack();afx_msg void OnDiv();afx_msg void OnGo();afx_msg void OnOn();afx_msg void OnSub();afx_msg void OnTim();afx_msg void OnXsd();afx_msg void OnZfh();afx_msg void OnAbtath();//}}AFX_MSGDECLARE_MESSAGE_MAP()};CPP文件CCacl2Dlg::CCacl2Dlg(CWnd* pParent /*=NULL*/): CDialog(CCacl2Dlg::IDD, pParent){//{{AFX_DATA_INIT(CCacl2Dlg)m_x = 0.0;//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);m_first=0.0;m_second=0.0; //该行以下为初始化m_firstz=0;m_firstx=0.0;m_secondz=0;m_secondx=0.0;m_firx=FALSE;m_secx=FALSE;m_firxw=0;m_secxw=0;m_firzorf=1;m_seczorf=1;m_EnterSec=FALSE;m_result=0.0;m_ForS=1;m_mfir=0.0;m_msec=0.0;m_mfun=0;m_sfmf=FALSE;m_sfms=FALSE;m_sfmfun=FALSE;}void CCacl2Dlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CCacl2Dlg)DDX_Control(pDX, IDC_RESULT, m_xedit);DDX_Text(pDX, IDC_RESULT, m_x);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CCacl2Dlg, CDialog)//{{AFX_MSG_MAP(CCacl2Dlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_0, On0)ON_BN_CLICKED(IDC_1, On1)ON_BN_CLICKED(IDC_2, On2)ON_BN_CLICKED(IDC_3, On3)ON_BN_CLICKED(IDC_4, On4)ON_BN_CLICKED(IDC_5, On5)ON_BN_CLICKED(IDC_6, On6)ON_BN_CLICKED(IDC_7, On7)ON_BN_CLICKED(IDC_8, On8)ON_BN_CLICKED(IDC_9, On9)ON_BN_CLICKED(IDC_ADD, OnAdd)ON_BN_CLICKED(IDC_BACK, OnBack)ON_BN_CLICKED(IDC_DIV, OnDiv)ON_BN_CLICKED(IDC_GO, OnGo)ON_BN_CLICKED(IDC_ON, OnOn)ON_BN_CLICKED(IDC_SUB, OnSub)ON_BN_CLICKED(IDC_TIM, OnTim)ON_BN_CLICKED(IDC_XSD, OnXsd)ON_BN_CLICKED(IDC_ZFH, OnZfh)ON_BN_CLICKED(IDC_ABTATH, OnAbtath)//}}AFX_MSG_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CCacl2Dlg message handlersvoid CCacl2Dlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);}}// If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model,// this is automatically done for you by the framework.void CCacl2Dlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();}}// The system calls this to obtain the cursor to display while the user drags // the minimized window.HCURSOR CCacl2Dlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}void CCacl2Dlg::On0() //输入0{// TODO: Add your control notification handler code hereAddNum(0);}void CCacl2Dlg::On1() //输入1{// TODO: Add your control notification handler code hereAddNum(1);}void CCacl2Dlg::On2() //输入2{// TODO: Add your control notification handler code hereAddNum(2);}void CCacl2Dlg::On3() //输入3{// TODO: Add your control notification handler code here AddNum(3);}void CCacl2Dlg::On4() //输入4{// TODO: Add your control notification handler code here AddNum(4);}void CCacl2Dlg::On5() //输入5{// TODO: Add your control notification handler code here AddNum(5);}void CCacl2Dlg::On6() //输入6{// TODO: Add your control notification handler code here AddNum(6);}void CCacl2Dlg::On7() //输入7{// TODO: Add your control notification handler code here AddNum(7);}void CCacl2Dlg::On8() //输入8{// TODO: Add your control notification handler code here AddNum(8);}void CCacl2Dlg::On9() //输入9{// TODO: Add your control notification handler code here AddNum(9);}void CCacl2Dlg::OnAdd() //输入+{// TODO: Add your control notification handler code hereAddFun(1);}void CCacl2Dlg::OnBack() //按back键{// TODO: Add your control notification handler code hereif(m_ForS==1) //如果此时在输入第一个数{if(m_firx==FALSE) //如果此时在输入整数部分{ if(m_firstz<10) //如果整数部分小于10{m_firstz=0; //改为0m_firzorf=1; //置符号为正}else{int y1=(int)m_firstz;//y1为一与整数部分相等的数y1/=10; //去掉个位数m_firstz=y1;}}else //如果在输入小数部分{if(m_firxw==1) //此时小数部分只有一位{m_firstx=0.0;m_firxw=0;m_firx=FALSE;//小数部分清为0}else{int y2=(int)(m_firstx*pow(10,m_firxw)); //取一整数与小数点所有的数表示的整数相等,如123等于0.123的小数部分表示的数y2/=10;m_firxw--; //去掉最后一位m_firstx=y2*pow(10,(-1)*m_firxw);}}m_first=m_firzorf*(m_firstz+m_firstx); //计算出第一个数m_x=m_first;UpdateData(FALSE); //显示它}else if(m_ForS==2) //如果在输入第二个数,处理方法同第一个数 {if(m_secx==FALSE){if(m_secondz<10){m_secondz=0;m_seczorf=1;}else{int y3=(int)m_secondz;y3/=10;m_secondz=y3;}}else{if(m_secxw==1){m_secondx=0.0;m_secxw=0;m_secx=FALSE;}else{int y4=(int)(m_secondx*pow(10,m_secxw));y4/=10;m_secxw--;m_secondx=y4*pow(10,(-1)*m_secxw);}}m_second=m_seczorf*(m_secondz+m_secondx);m_x=m_second;UpdateData(FALSE);}}void CCacl2Dlg::OnDiv() //输入/{// TODO: Add your control notification handler code hereAddFun(4);}void CCacl2Dlg::OnGo() //按=号运算{// TODO: Add your control notification handler code hereif(m_sfmf==TRUE&&m_sfms==TRUE&&m_sfmfun==TRUE) //如果记着第一,二个数和运算符,即上次算完后未输入数,而再次按={if(m_mfun==1)m_result=m_mfir+m_msec; //m_fun为1,则用上次的数和符号加,下同else if(m_mfun==2)m_result=m_mfir-m_msec; //m_fun为2,则减,下同else if(m_mfun==3)m_result=m_mfir*m_msec; //为3,则乘,下同else if(m_mfun==4)m_result=m_mfir/m_msec; //为4,则除,下同m_sfmf=TRUE;m_sfms=TRUE;m_sfmfun=TRUE; //记住参加运算的数和运算符m_mfir=m_result;m_msec=m_msec;m_mfun=m_mfun;}else if(m_sfmf==TRUE&&m_sfms==FALSE&&m_sfmfun==FALSE)//只记的第一数,如算完2+3=5后按*4={if(m_fun==1)m_result=m_mfir+m_second;else if(m_fun==2)m_result=m_mfir-m_second;else if(m_fun==3)m_result=m_mfir*m_second;else if(m_fun==4)m_result=m_mfir/m_second;m_sfmf=TRUE;m_sfms=TRUE;m_sfmfun=TRUE;m_mfir=m_result;m_msec=m_second;m_mfun=m_fun;}else if(m_sfmf=TRUE&&m_sfms==TRUE&&m_sfmfun==FALSE) //记住了第一个数,未输入第二个数,输入了运算符.如算完2+3=5后按*=结果为5*5=25;{m_second=m_mfir;if(m_fun==1)m_result=m_mfir+m_second;else if(m_fun==2)m_result=m_mfir-m_second;else if(m_fun==3)m_result=m_mfir*m_second;else if(m_fun==4)m_result=m_mfir/m_second;m_sfmf=TRUE;m_sfms=TRUE;m_sfmfun=TRUE;m_mfir=m_result;m_msec=m_second;m_mfun=m_fun;}else if(m_sfmf==FALSE&&m_sfms==FALSE&&m_sfmfun==FALSE)//第一二个数和运算符都不记的,记全重新输入,如算完2+3=5后输入4*6={if(m_EnterSec==FALSE)m_second=m_first;if(m_fun==1)m_result=m_first+m_second;else if(m_fun==2)m_result=m_first-m_second;else if(m_fun==3)m_result=m_first*m_second;else if(m_fun==4)m_result=m_first/m_second;m_sfmf=TRUE;m_sfms=TRUE;m_sfmfun=TRUE;m_mfir=m_result;m_msec=m_second;m_mfun=m_fun;}m_x=m_result;UpdateData(FALSE); //显示结果m_first=0;m_second=0.0;m_firstz=0;m_firstx=0.0;m_secondz=0;m_secondx=0.0;m_firx=FALSE;m_secx=FALSE;m_firxw=0;m_secxw=0;m_firzorf=1;m_seczorf=1;m_ForS=1;m_EnterSec=FALSE;}void CCacl2Dlg::OnOn() //按on键{// TODO: Add your control notification handler code here m_x=0.0; //恢复默认值,下同m_first=0.0;m_second=0.0;m_firstz=0;m_firstx=0.0;m_secondz=0;m_secondx=0.0;m_firx=FALSE;m_secx=FALSE;m_firxw=0;m_secxw=0;m_firzorf=1;m_seczorf=1;m_ForS=1;m_mfir=0.0;m_msec=0.0;m_mfun=0;m_sfmf=FALSE;m_sfms=FALSE;m_sfmfun=FALSE;m_EnterSec=FALSE;UpdateData(FALSE);}void CCacl2Dlg::OnSub() //输入-{// TODO: Add your control notification handler code here AddFun(2);}void CCacl2Dlg::OnTim() //输入*{// TODO: Add your control notification handler code hereAddFun(3);}void CCacl2Dlg::OnXsd() //按小数点.{// TODO: Add your control notification handler code hereif(m_ForS==1)m_firx=TRUE; //此时在输入第一个数,第一个数指示十是否该输入小数部分变量置为真else if(m_ForS==2)m_secx=TRUE; //在输入第二个数}void CCacl2Dlg::OnZfh() //按+/-键{// TODO: Add your control notification handler code hereif(m_ForS==1) //此时在输入第一个数{m_firzorf=-1; //指示符置为-1m_first*=-1;m_x=m_first;UpdateData(FALSE);}else{m_seczorf=-1;m_second*=-1;m_x=m_second;UpdateData(FALSE);}}void CCacl2Dlg::AddNum(int i) //输入数字是时的处理函数{if(m_ForS==1){if(m_firx==FALSE) //整数数部分{m_firstz*=10;m_firstz+=i;}else //小数部分{m_firxw++;m_firstx+=pow(10,(-1)*m_firxw)*i;}m_first=m_firzorf*(m_firstz+m_firstx);m_x=m_first; m_sfmf=FALSE;m_mfir=0;UpdateData(FALSE);}else if(m_ForS==2) //第二个数,处理同第一个数{m_EnterSec=TRUE; //将指示是否输入第二个数的变量置为真 if(m_secx==FALSE){m_secondz*=10;m_secondz+=i;}else{m_secxw++;m_secondx+=pow(10,(-1)*m_secxw)*i;}m_second=m_seczorf*(m_secondz+m_secondx);m_sfms=FALSE;m_msec=0;m_x=m_second;UpdateData(FALSE);}}void CCacl2Dlg::AddFun(int j) //输入运算符时的处理函数{if(m_sfmf==TRUE&&m_sfmfun==FALSE&&m_EnterSec==TRUE){ if(m_fun==1)m_result=m_mfir+m_second;else if(m_fun==2)m_result=m_mfir-m_second;else if(m_fun==3)m_result=m_mfir*m_second;else if(m_fun==4)m_result=m_mfir/m_second;m_x=m_result;m_sfmf=TRUE;m_mfir=m_result;UpdateData(FALSE); m_EnterSec=FALSE;m_firstz=0;m_firstx=0;m_firxw=0;m_firzorf=1;m_second=0;m_secondz=0;m_secondx=0;m_secxw=0;m_ForS=2;m_seczorf=1;if(j==1)m_fun=1;else if(j==2)m_fun=2;else if(j==3)m_fun=3;else if(j==4)m_fun=4;}else if(m_sfmf==FALSE&&m_sfmfun==FALSE&&m_EnterSec==TRUE) //如果此时第二个数存在.则运算,例如输入2+3后按*键{if(m_fun==1)m_result=m_first+m_second;else if(m_fun==2)m_result=m_first-m_second;else if(m_fun==3)m_result=m_first*m_second;else if(m_fun==4)m_result=m_first/m_second;m_x=m_result;m_first=m_result;UpdateData(FALSE); m_EnterSec=FALSE;m_sfmf=TRUE;m_mfir=m_result;m_firstz=0;m_firstx=0;m_firxw=0;m_firzorf=1;m_second=0;m_secondz=0;m_secondx=0;m_secxw=0;m_ForS=2;m_seczorf=1;if(j==1)m_fun=1;else if(j==2)m_fun=2;else if(j==3)m_fun=3;else if(j==4)m_fun=4;}else{if(j==1)m_fun=1;else if(j==2)m_fun=2;else if(j==3)m_fun=3;else if(j==4)m_fun=4;m_ForS=2;m_x=0;UpdateData(FALSE);}m_mfun=0;m_sfmfun=FALSE;}(注:素材和资料部分来自网络,供参考。