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

合集下载

简易计算器程序源代码

简易计算器程序源代码

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

C语言简单计算器程序源代码

C语言简单计算器程序源代码

C语言简单计算器程序源代码以下是一个简单计算器程序的C语言源代码,超过1200字: ```c#include <stdio.h>int maichar operator;double num1, num2, result;printf("请输入操作数1: ");scanf("%lf", &num1);printf("请输入操作符(+, -, *, /): ");scanf(" %c", &operator);printf("请输入操作数2: ");scanf("%lf", &num2);switch (operator)case '+':result = num1 + num2;printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result); break;case '-':result = num1 - num2;printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result); break;case '*':result = num1 * num2;printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result); break;case '/':if (num2 != 0)result = num1 / num2;printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result); } elseprintf("错误:被除数不能为0!\n");}break;default:printf("错误:无效的操作符!\n");break;}return 0;```这个程序实现了一个简单的计算器,可以根据用户输入的操作数和操作符进行加、减、乘、除的四则运算,并输出结果。

速算,简易计算器c语言代码,可实现加减乘除

速算,简易计算器c语言代码,可实现加减乘除

速算,简易计算器c语⾔代码,可实现加减乘除#include"stdio.h"#include"math.h"#include"stdlib.h"struct optrstyle{int top;char stack[20];}struct opndstyle{int top;int stack[20];}void main(){char ch;while(1){printf("-----------------------------------------\n");printf("|-----------欢迎来到速算24--------------|\n");printf("|----------是否开始游戏------------|\n");printf("|--------- 开始游戏请按'Y'-------------|\n");printf("|--------- 退出游戏请按其他键-------------|\n");printf("-----------------------------------------\n");scanf("%c",&ch);if(ch=='Y' or ch=='y'){}elsebreak;}}int EvaluateExpression(){// 算术表达式求值的算符优先算法。

设OPTR 和OPND 分别为运算符栈和运算数栈,OP 为运算符集合。

InitStack(OPTR);Push(OPTR,'#');InitStack(OPND);c = getchar();while(c!='#' || GetTop(OPTR)!='#'){if(!In(c,OP)){Push((OPND,c);c = getchar();} // 不是运算符则进栈elseswitch(Precede(GetTop(OPTR),c)){case '<': // 栈顶元素优先权低Push(OPTR,c);c = getchar();break;case '=': // 脱括号并接收下⼀字符Pop(OPTR,x); c = getchar();break;case '>': // 退栈并将运算结果⼊栈Pop(OPTR,theta);Pop(OPND,b);Pop(OPND,a);Push(OPND,Operate(a,theta,b));break;}// switch}// whilereturn GetTop(OPND);}// EvaluateExpressionint changecard( char a[]){if()void InitStack(Stack &S){S.top=-1;}int Pop1(Stack &S){if(S.top==-1){printf("stack is empty!");exit (1);}ElemType temp=S.stack[S.top]; S.top--;return temp;}int GetTop1(Stack &S){if(S.top==-1){printf("stack is empty!");exit (1);}return S.stack[S.top];}char Pop2(Stack &S){if(S.top==-1){printf("stack is empty!");exit (1);}ElemType temp=S.stack[S.top]; S.top--;return temp;char GetTop2(Stack &S){if(S.top==-1){printf("stack is empty!");exit (1);}return S.stack[S.top];}char Precede(char a,char b)//算符优先级函数{ char temp;switch(a){case '+','-':{if (b=='*' or b=='/' or b=='(')temp='<';else temp='>';}break;case '*','/':{if(b=='(')temp='<';else temp='>';}break;case '(':{if(b==')')temp='=';elsetemp='<';}break;case ')':temp='>';break; case '#':{if(b=='#') temp='='; else temp='<'; }break; default break; }return temp; }。

C编写简易计算器附源代码超详细共16页文档

C编写简易计算器附源代码超详细共16页文档

超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用Windows窗体应用程序,并命名为Calc,如下图所示:二、向窗体中拖入需要的控件,如下图所示:(完成效果图)结果显示区(作者博客左边的文本框)是TextBox控件,并修改其name为txtShow ,按键0~9为Button控件,并将其name分别修改为btn_0、btn_1、btn_2、btn_3、btn_4、btn_5、btn_6、btn_7、btn_8、btn_9;按键【负数】的name值修改为btn_sign,按键【.】的name 修改为btn_dot,按键【+ - * /】的name值分别修改为btn_add、btn_sub、btn_mul、btn_div,按键【=】的name值修改为btn_equ,按键【倒数】的name值修改为btn_rev,按键【平方】的name值修改为btn_sqr,按键【开方】的name值修改为btn_sqrt。

右边的计算器图片空间是PictureBox,作者博客控件是LinkLabel,可以不添加,以上所有控件均可按照需求添加,只保留自己需要的按钮控件和textbox控件即可。

三、代码部分(含解释),采用switch多分支语句编写using System;using System.Drawing;using System.Collections;using SystemponentModel;using System.Windows.Forms;using System.Data;namespace Calc///<summary>/// QQ:479340056 温柔一刀C#简易计算器的实现///</summary>public class CalcForm : System.Windows.Forms.Formprivate System.Windows.Forms.Button btn_0;private System.Windows.Forms.Button btn_1;private System.Windows.Forms.Button btn_2;private System.Windows.Forms.Button btn_3;private System.Windows.Forms.Button btn_4;private System.Windows.Forms.Button btn_5;private System.Windows.Forms.Button btn_6;private System.Windows.Forms.Button btn_7;private System.Windows.Forms.Button btn_8;private System.Windows.Forms.Button btn_9;private System.Windows.Forms.Button btn_add;private System.Windows.Forms.Button btn_sub;private System.Windows.Forms.Button btn_mul;private System.Windows.Forms.Button btn_div;private System.Windows.Forms.Button btn_sqrt;private System.Windows.Forms.Button btn_sign;private System.Windows.Forms.Button btn_equ;private System.Windows.Forms.Button btn_dot;private System.Windows.Forms.Button btn_rev;private System.Windows.Forms.TextBox txtShow;private System.Windows.Forms.Button btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;///<summary>///必需的设计器变量。

c语言科学计算器程序编写

c语言科学计算器程序编写

以下是一个简单的C语言科学计算器程序,可以执行基本的数学运算和科学计算:```c#include <stdio.h>#include <math.h>int main() {char op;double num1, num2, result;printf("请输入一个数学表达式(例如:2 + 3):\n"); scanf("%lf %c %lf", &num1, &op, &num2);switch(op) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':if(num2 == 0) {printf("错误:除数不能为0!\n");return 0;} else {result = num1 / num2;}break;case '^':result = pow(num1, num2);break;default:printf("错误:不支持的操作符!\n");return 0;}printf("结果为:%lf\n", result);return 0;}```该程序首先要求用户输入一个数学表达式,然后使用scanf函数读取表达式中的操作数和运算符。

接下来,使用switch语句根据运算符执行相应的计算,并将结果存储在result变量中。

最后,程序输出计算结果。

C#实现简易计算器功能(附源码)

C#实现简易计算器功能(附源码)

C#实现简易计算器功能(附源码)本⽂实例为⼤家分享了C#实现简易计算器功能的具体代码,供⼤家参考,具体内容如下剖析:1、先设计界⾯(按钮、⽂本框(⼀个显⽰算式,⼀个显⽰结果))布局2、单击按钮将其对应内容显⽰在⽂本框中3、单击符号(+、-、×、÷、%)时将第⼀次输⼊的数储存起来4、单击等号时将第⼆次输⼊的数存储起来并将第⼀次输⼊的数与第⼆次输⼊的数按照所单击的符号进⾏运算将结果显⽰在第⼀个⽂本框中5、单击C时将两个⽂本框中的内容清空重点:1、声明⼀个bool类型的变量⽤于实现单击符号再次输⼊数字时第⼀次输⼊的数字清空显⽰第⼆次输⼊的数字2、声明两个double类型的变量⽤于装第⼀次输⼊的数和装第⼆次输⼊的数3、声明⼀个string类型的变量⽤于判断运算符号界⾯布局:具体代码如下:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace Test_Calculator{public partial class Form1 : Form{public Form1(){InitializeComponent();}//声明三个变量string type; //符号类型double x;//装第⼀个数(按符号(+-×÷%)时textbox1中的数字)double y;//装第⼆个数(按等号时textbox1中的数字)bool c=false;private void Form1_Load(object sender, EventArgs e){this.CenterToScreen();//窗体居中显⽰this.Text = "计算器";this.FormBorderStyle = FormBorderStyle.FixedToolWindow; textBox1.ReadOnly = true;//⽂本框只读textBox2.TabIndex = 0;//光标焦点在textbox2中}private void button1_Click(object sender, EventArgs e){if (c==true){c = false;textBox1.Text = "";}textBox1.Text += "1";textBox2.Text += "1";}private void button2_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "2";textBox2.Text += "2";}private void button3_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "3";textBox2.Text += "3";}private void button4_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "4";textBox2.Text += "4";}private void button5_Click(object sender, EventArgs e){if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "5";textBox2.Text += "5";}private void button6_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "6";textBox2.Text += "6";}private void button7_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "7";textBox2.Text += "7";}private void button8_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "8";textBox2.Text += "8";}private void button9_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "9";textBox2.Text += "9";}private void button10_Click(object sender, EventArgs e) {if (c == true){c = false;textBox1.Text = "";}textBox1.Text += "0";textBox2.Text += "0";}private void button11_Click(object sender, EventArgs e) {textBox1.Text += ".";textBox2.Text += ".";}private void button12_Click(object sender, EventArgs e) {textBox1.Text = "";textBox2.Text = "";}private void button13_Click(object sender, EventArgs e) {c = true;type = "+";textBox2.Text += "+";x = double.Parse(textBox1.Text);}private void button14_Click(object sender, EventArgs e){c = true;type = "-";textBox2.Text += "-";x = double.Parse(textBox1.Text);}private void button15_Click(object sender, EventArgs e){c = true;type = "×";textBox2.Text += "×";x = double.Parse(textBox1.Text);}private void button16_Click(object sender, EventArgs e){c = true;type = "÷";textBox2.Text += "÷";x = double.Parse(textBox1.Text);}private void button18_Click(object sender, EventArgs e){c = true;type = "%";textBox2.Text += "%";x = double.Parse(textBox1.Text);}private void button17_Click(object sender, EventArgs e){y = double.Parse(textBox1.Text);//法⼀while (type=="+"){textBox1.Text = (x + y).ToString();textBox2.Text += "=" + textBox1.Text;return;}while (type == "-"){textBox1.Text = (x - y).ToString();textBox2.Text += "=" + textBox1.Text;return;}while (type == "×"){textBox1.Text = (x * y).ToString();textBox2.Text += "=" + textBox1.Text;return;}while (type == "÷"){if (y!=0){textBox1.Text = (x / y).ToString();textBox2.Text += "=" + textBox1.Text;}else{MessageBox.Show("请重新输⼊","错误",MessageBoxButtons.OK,rmation); textBox1.Text = "";textBox2.Text = "";}return;}while (type == "%"){textBox1.Text = (x % y).ToString();textBox2.Text += "=" + textBox1.Text;return;}//法⼆://if (type=="+")//{// textBox1.Text=(x + y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="-")//{// textBox1.Text = (x - y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="×")//{// textBox1.Text = (x * y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="÷")//{// textBox1.Text = (x / y).ToString();// textBox2.Text += "=" + textBox1.Text; //}//if (type=="%")//{// textBox1.Text = (x % y).ToString();// textBox2.Text += "=" + textBox1.Text; //}}}}效果图:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

C语言程序设计之简单计算器

C语言程序设计之简单计算器

C语言程序设计之简单计算器```C#include <stdio.h>int maichar operator;double num1, num2;printf("Enter the first number: ");scanf("%lf", &num1);printf("Enter the operator (+, -, *, /): ");scanf(" %c", &operator);printf("Enter the second number: ");scanf("%lf", &num2);switch(operator)case '+':printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2); break;case '-':printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2); break;case '*':printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);break;case '/':if(num2 != 0)printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);} elseprintf("Error: Division by zero is not allowed\n");}break;default:printf("Error: Invalid operator\n");break;}return 0;```这段代码是一个简单的C语言计算器程序,用户可以输入两个数字和一个操作符,程序将根据用户输入的操作符进行相应的计算,并输出结果。

简易计算器源代码--java

简易计算器源代码--java

package calculator;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.math.BigDecimal;import javax.swing.*;public class Operation extends JFrame implements ActionListener{/****/private static final long serialVersionUID = 1L;private final String str[] = {"7","8","9","/","4","5","6","*","1","2", "3","-",".","0","=","+"};private final JButton[] JB = new JButton[str.length];private final JButton reset = new JButton("CE");private final JTextField display = new JTextField("");Operation(){super("计算器");JPanel panel1 = new JPanel(new BorderLayout());JPanel panel2 = new JPanel(new GridLayout(4,4));panel1.add(BorderLayout.CENTER, display);panel1.add(BorderLayout.EAST, reset);int i;for( i = 0;i < str.length;i++){JB[i] = new JButton(str[i]);panel2.add(JB[i]);}getContentPane().setLayout(new BorderLayout());getContentPane().add(BorderLayout.NORTH,panel1);getContentPane().add(BorderLayout.SOUTH, panel2);setSize(800,800);for(i = 0;i < str.length;i++){JB[i].addActionListener(this);}reset.addActionListener(this);display.addActionListener(this);setVisible(true);setDefaultCloseOperation((WindowConstants.DISPOSE_ON_CLOSE));pack();}public void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根Object target = e.getSource();String label = e.getActionCommand();if(target == reset){handlereset();}else if("0123456789.".indexOf(label)>=0){handleNumber(label);}elsehandleOperator(label);}private void handleNumber(String key) {// TODO 自动生成的方法存根if ((isFirstDigit)&&("0123456789".indexOf(key)>=0))display.setText(key);else if ((key.equals(".")))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}boolean isFirstDigit = true;double number1 = 0.0;double number2 = 0.0;String operator = "=";BigDecimal df ;private void handlereset() {// TODO 自动生成的方法存根display.setText("");isFirstDigit = true;operator = "=";}public void handleOperator(String key) {if (operator.equals("+")){number1 = Double.valueOf(display.getText());number2 = add(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("-")){number1 = Double.valueOf(display.getText());number2 = sub(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("*")){number1 = Double.valueOf(display.getText());number2 = mul(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("/")){number1 = Double.valueOf(display.getText());if(number1 == 0)display.setText("error");else{number2 = div(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}}else if (operator.equals("=")){number2 = Double.valueOf(display.getText());display.setText(String.valueOf(number2));}operator = key;isFirstDigit = true;}private double div(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 / key2;return result;}private double mul(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 * key2;return result;}private double sub(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = key1 - key2;return result;}private double add(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = number1 + number2;return result;}public static void main(String[] args) {new Operation();}}。

编写一个简易计算器的源代码

编写一个简易计算器的源代码

AStack.h#ifndef ASTACK_HEADER#define ASTACK_HEADER#include <iostream>using namespace std;template <class Elem> class AStack{private:int size;int top;Elem* listArray;public:AStack(){ size = 100; top = 0; listArray = new Elem[100]; }~AStack(){ delete [] listArray; }void clear() { top = 0; }bool push(Elem& item){if (top == size) return false;else { listArray[top++] = item; return true; } }bool pop(Elem& it){if (top == 0) return false;else { it = listArray[--top]; return true; }}bool topValue(Elem& it) const{if (top == 0) return false;else { it = listArray[top - 1]; return true; } }int length() const { return top; }};#endifFunction.cpp#include "function.h"#include "AStack.h"#include <math.h>#include <stdio.h>void calUserInfo(){cout<<"\t* 智能计算器V1.0*"<<endl;cout<<"\t*********************"<<endl;cout<<"\t* 1 * 2 * 3 * + * - *"<<endl;cout<<"\t* 4 * 5 * 6 * * * / *"<<endl;cout<<"\t* 7 * 8 * 9 * 0 * % *"<<endl;cout<<"\t* & * ^ * = * ( * ) *"<<endl;cout<<"\t*********************"<<endl; }int isp(char& ch){switch(ch){case '=':return 0;break;case '+':case '-':return 3;break;case '*':case '/':case '%':return 5;case '(':return 1;break;case ')':return 8;break;case '^':case '&':return 7;break;}}int osp(char& ch) {switch(ch) {case '=':return 0;break;case '+':case '-':return 2;break;case '*':case '/':case '%':return 4;break;case '(':return 8;break;case ')':break;case '^':case '&':return 6;break;}}double extract(double x,double y){return pow(x,1/y);}bool cal(char op, double x, double y, double& r) {int o = 0;switch(op){case '-':r = x - y;break;case '+':r = x + y;break;case '/':r = x / y;break;case '%':(int) o = (int)x % (int)y;r = (double)o;break;case '*':r = x * y;case '&':r = extract(x,y);break;case '^':r = pow(x,y);break;}return true;}bool isDigit(char ch){if (((int)ch >= 48) && ((int)ch <= 57))return true;else return false;}bool isPoint(char ch){if (ch == '.')return true;else return false;}bool isOperator(char ch){if ((ch == '=') || (ch == '-') || (ch == '+') || (ch == '(') || (ch == ')') || (ch == '*') || (ch == '&') ||(ch == '/') ||(ch == '%') ||(ch == '^'))return true;else return false;}double turnDigit(char ch){double value;value = (double)ch - 48;return value;}double newDigit(double prior_digit, double now_digit, bool isHavePoint, double point_num){double value;if(!isHavePoint){value = prior_digit*10 + now_digit;}else{value = prior_digit + now_digit/(pow(10,point_num));}return value;}Function.h#ifndef FUNCTION_HEADER#define FUNCTION_HEADER//友好的用户界面void calUserInfo();//用于记录处于栈内的优先级int isp(char& ch);//用于记录栈外的优先级int osp(char& ch);//相当于value = x op y;如果cal成功,然后将value的值返回r,用r来保存bool cal(char op, double x, double y, double& r);//判断是否为字符bool isDigit(char ch);//判断是否为小数点bool isPoint(char ch);//判断是否为操作运算符bool isOperator(char ch);//将数字的字符状态转化成double状态double turnDigit(char ch);//如果几个数字或加一个小数点连在一起,这说明他们是同一个数字的不同位数,此函数将不同连在一起的数字//组成新的数字double newDigit(double prior_digit, double now_digit, bool isHavePoint, double point_num);#endifMain.cpp#include "AStack.h"#include "function.h"#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;int main(){char str[100] = "\0";AStack<double> opnd; //用于存放数据AStack<char> optr; //用于存放操作符char now_ch = '='; //用于记录当前字符char prior_ch = '\0'; //用于记录前一个字符double now_dig = 0; //用于记录当前一个数字double prior_dig = 0; //用于记录前一个数字double value = 0; //用于存放计算后的值bool point = false; //用于判断是否有小数点int point_num = 1; //用于记录数字后面的小数点位数char topValue; //用于记录opnd的top上的值char option = 'Y'; //用于判断是否要继续运算do{prior_dig = 0; //在opnd中提前放一个0now_ch = '=';opnd.push(prior_dig);optr.push(now_ch);system("cls");calUserInfo();cout << "请输入表达式(以等号结束):" << endl;cin >> str;bool exitPoint = false;/*对每个字符的处理*/for(int i = 0; i < strlen(str); i++){now_ch = str[i];/*判断是不是数字以及相关操作*/if (isDigit(now_ch)){now_dig = turnDigit(now_ch);if (isDigit(prior_ch)){opnd.pop(prior_dig);if(exitPoint){point = true;now_dig = newDigit(prior_dig, now_dig,point,point_num);point_num++;}elsenow_dig = newDigit(prior_dig, now_dig,point,point_num);}if(isPoint(prior_ch)){opnd.pop(prior_dig);now_dig = newDigit(prior_dig, now_dig,point,point_num);exitPoint = true;point_num++;}value = now_dig;opnd.push(now_dig);prior_ch = now_ch;}/*判断是不是小数点以及相关操作*/else if (isPoint(now_ch)){point = true;prior_ch = now_ch;}/*判断是不是操作符以及相关操作*/else if (isOperator(now_ch)){/*对用于数字操作的相关标记量进行清空,方便下一次数字操作*/point = false;point = 0;exitPoint = false;point_num = 1;/*看optr中是否有操作符存在,若不存在,则只放一个操作符进去*//* 但不进行任何操作*/if(optr.length() <= 1){optr.push(now_ch);prior_ch = now_ch;}/*optr已有操作符存在的话,开始进行优先级的比较*/else{optr.pop(topValue);/* 栈内优先级小于栈外优先级*/if(isp(topValue) < osp(now_ch)){optr.push(topValue);optr.push(now_ch);prior_ch = now_ch;}/*栈内优先级大于栈外优先级*/else if(isp(topValue) > osp(now_ch)){if(now_ch == ')' && topValue == '('){break;}do{double x = 1,y = 0;opnd.pop(x);opnd.pop(y);if( cal(topValue,y,x,value) ){opnd.push(value);}if(!optr.pop(topValue))break;}while(isp(topValue) > osp(now_ch));// if((topValue != '('))if (now_ch != ')'){optr.push(topValue);optr.push(now_ch);}prior_ch = now_ch;}/*其他情况报错*/elsebreak;}}/*其他情况报错*/elsecout << "输入的表达式错误,请检查!" << endl; }optr.pop(prior_ch);/*打印最后的计算值*/if(prior_ch == '='){cout << "最终得出的数据为: " << value << endl;}elsecout << "输入的表达式错误,请检查!" << endl;/*判断是否还要继续*/cout << "是否继续? ,继续'Y'/结束'N' :" << endl;cin >> option;/*清空数字栈和操作符栈*/opnd.clear();optr.clear();}while(option == 'Y');return 0;}。

自己写的计算器程序源代码

自己写的计算器程序源代码

1,java语言的,写的不是很,有个不是很好的界面import java.awt.*;import java.awt.event.*;class cal extends WindowAdapter implements WindowListener,ActionListener{boolean h=false;boolean k=false;double a=0.0;double b=0.0;double c=0.0;String v;Frame f;Panel p1,p2,p3;Menu m1,m2,m3;MenuBar s;TextField t;Dialog d,d1;TextArea l,l1;public void dis(){f=new Frame("计算器");Da(f);Me();p1=new Panel();p2=new Panel();p3=new Panel();p2.setLayout(new GridLayout(4,5,5,5));p3.setLayout(new GridLayout(3,4,5,5));t=new TextField("0",25);t.setEditable(false);p1.add(t);f.add(p1,"North");f.setSize(220,320);f.setLocation(200,200);f.setBackground(Color.lightGray);f.addWindowListener(this);Button []b=new Button[32];String[]a={"7","8","9","+","clear","4","5","6","-","sqrt","1","2","3","×","cqrt","0",".","+/-","/","ln","log10","log(x)Y","%","x^y","sin","cos","tan","exp","asin","acos","atan","="};int i,j;for (i=0;i<=19;i++){b[i]=new Button(a[i]);b[i].addActionListener(this);p2.add(b[i]);}for (j=20;j<=31;j++){b[j]=new Button(a[j]);b[j].addActionListener(this);p3.add(b[j]);}f.add(p2,"Center");f.add(p3,"South");f.setV isible(true);}public void Me(){s=new MenuBar();f.setMenuBar(s);m1=new Menu("编辑(E)");m2=new Menu("查看(V)");m3=new Menu("帮助(H)");s.add(m1);s.add(m2);s.add(m3);m1.add(new MenuItem("Open"));m1.add(new MenuItem("Copy"));m1.add(new MenuItem("pastye"));m1.add(new MenuItem("Save",new MenuShortcut(KeyEvent.VK_S)));m1.add(new MenuItem("Exit"));m2.add(new MenuItem("Standard"));m2.add(new MenuItem("Science"));m1.addActionListener(this);m2.addActionListener(this);m3.add(new MenuItem("About"));m3.add(new MenuItem("Instructions"));m3.addActionListener(this);}public void windowClosing(WindowEvent e){if(e.getSource()==d)d.setV isible(false);else if(e.getSource()==d1)d1.setV isible(false);elseSystem.exit(0);}public void Da(Frame f){d=new Dialog(f,"Dialog",true);d.setSize(36,120);d.setLocation(200,200);d1=new Dialog(f,"使用说明",true);d1.setSize(200,202);d1.setLocation(200,200);l=new TextArea("",4,15,TextArea.SCROLLBARS_VERTICAL_ONLY);l1=new TextArea("",4,15,TextArea.SCROLLBARS_NONE);d.add(l);d1.add(l1);d.addWindowListener(this);d1.addWindowListener(this);}public void actionPerformed(ActionEvent e){float x;String q=e.getActionCommand();if(q=="Exit")System.exit(0);if(q=="About"){l.setText(" 该计算器实现加减乘除开方等基本运算,而且能够计算三角函数以及反三角函数的值,能够进行对数、乘方运算。

简单计算器设计源代码

简单计算器设计源代码
Switch mSwitch=new Switch();
Button btn0,btn1,btn2,btn3,btn4,btn5;
Button btn6,btn7,btn8,btn9;
EditText et=null;
Button btnC,btnadd,btnsub,btnmul,btndiv,btnequal,btnpoint;
<Button
android:id="@+id/btn_seven_main"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="1"
android:gravity="center"
android:textSize="40sp"
android:text="/"/>
</LinearLayout>
</LinearLayout>
源代码:
package com.example.num;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
android:text="-"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layoutid:orientation="horizontal" >

简单的计算器源代码

简单的计算器源代码

//计算器,已经编译通过import java.awt.*;import java.awt.event.*;import javax.swing.*;public class testZ extends JFrame implements ActionListener{private JPanel jPanel1,jPanel2;private JTextField resultField;private JButton s1,s2,s3,s4,s5,s6,s7,s8,s9,s0,b1,b2,b3,b4,f1,f2; private boolean end,add,sub,mul,div;private String str;private double num1,num2;public testZ(){super("计算器");setSize(300,240);Container con=getContentPane();con.setLayout(new BorderLayout());jPanel1=new JPanel();jPanel1.setLayout(new GridLayout(1,1));jPanel2=new JPanel();jPanel2.setLayout(new GridLayout(4,4));resultField=new JTextField("0");jPanel1.add(resultField);con.add(jPanel1,BorderLayout.NORTH);s1=new JButton(" 1 "); s1.addActionListener(this);s2=new JButton(" 2 "); s2.addActionListener(this);s3=new JButton(" 3 "); s3.addActionListener(this);s4=new JButton(" 4 "); s4.addActionListener(this);s5=new JButton(" 5 "); s5.addActionListener(this);s6=new JButton(" 6 "); s6.addActionListener(this);s7=new JButton(" 7 "); s7.addActionListener(this);s8=new JButton(" 8 "); s8.addActionListener(this);s9=new JButton(" 9 "); s9.addActionListener(this);s0=new JButton(" 0 "); s0.addActionListener(this);b1=new JButton(" + "); b1.addActionListener(this);b2=new JButton(" - "); b2.addActionListener(this);b3=new JButton(" * "); b3.addActionListener(this);b4=new JButton(" / "); b4.addActionListener(this);f1=new JButton(" . "); f1.addActionListener(this);f2=new JButton(" = "); f2.addActionListener(this);jPanel2.add(s1);jPanel2.add(s2);jPanel2.add(s3);jPanel2.add(b1);jPanel2.add(s4);jPanel2.add(s5);jPanel2.add(s6);jPanel2.add(b2);jPanel2.add(s7);jPanel2.add(s8);jPanel2.add(s9);jPanel2.add(b3);jPanel2.add(s0);jPanel2.add(f1);jPanel2.add(f2);jPanel2.add(b4);con.add(jPanel2,BorderLayout.CENTER);}public void num(int i){String s = null;s=String.valueOf(i);if(end){//如果数字输入结束,则将文本框置零,重新输入resultField.setText("0");end=false;}if((resultField.getText()).equals("0")){//如果文本框的内容为零,则覆盖文本框的内容resultField.setText(s);}else{//如果文本框的内容不为零,则在内容后面添加数字str = resultField.getText() + s;resultField.setText(str);}}public void actionPerformed(ActionEvent e){ //数字事件 if(e.getSource()==s1)num(1);else if(e.getSource()==s2)num(2);else if(e.getSource()==s3)num(3);else if(e.getSource()==s4)num(4);else if(e.getSource()==s5)num(5);else if(e.getSource()==s6)num(6);else if(e.getSource()==s7)num(7);else if(e.getSource()==s8)num(8);else if(e.getSource()==s9)num(9);else if(e.getSource()==s0)num(0);//符号事件else if(e.getSource()==b1)sign(1);else if(e.getSource()==b2)sign(2);else if(e.getSource()==b3)sign(3);else if(e.getSource()==b4)sign(4);//等号else if(e.getSource()==f1){str=resultField.getText();if(str.indexOf(".")<=1){str+=".";resultField.setText(str);}}else if(e.getSource()==f2){num2=Double.parseDouble(resultField.getText());if(add){num1=num1 + num2;}else if(sub){num1=num1 - num2;}else if(mul){num1=num1 * num2;}else if(div){num1=num1 / num2;}resultField.setText(String.valueOf(num1));end=true;}}public void sign(int s){if(s==1){add=true;sub=false;mul=false;div=false;}else if(s==2){add=false;sub=true;mul=false;div=false;}else if(s==3){add=false;sub=false;mul=true;div=false;}else if(s==4){add=false;sub=false;mul=false;div=true;}num1=Double.parseDouble(resultField.getText()); end=true;}public static void main(String[] args){testZ th1=new testZ();th1.show();}}。

C语言编写的计算器源代码

C语言编写的计算器源代码

C语言编写的计算器源代码```c#include<stdio.h>#include<stdlib.h>#include<string.h>#include<ctype.h>#define MAX_EXPRESSION_SIZE 100//栈结构定义typedef structint top;double data[MAX_EXPRESSION_SIZE];} Stack;//初始化栈void initStack(Stack *s)s->top = -1;//入栈void push(Stack *s, double value)if (s->top == MAX_EXPRESSION_SIZE - 1)printf("Stack is full. Cannot push element.\n");} elses->data[++(s->top)] = value;}//出栈double pop(Stack *s)if (s->top == -1)printf("Stack is empty. Cannot pop element.\n"); return -1;} elsereturn s->data[(s->top)--];}//获取栈顶元素double peek(Stack *s)if (s->top == -1)return -1;} elsereturn s->data[s->top];}//判断运算符的优先级int getPriority(char operator)switch (operator)case '+':case '-':return 1;case '*':case '/':return 2;case '^':return 3;default:return -1;}//执行四则运算double performOperation(double operand1, double operand2, char operator)switch (operator)case '+':return operand1 + operand2;case '-':return operand1 - operand2;case '*':return operand1 * operand2;case '/':if (operand2 != 0)return operand1 / operand2;} elseprintf("Error: Division by zero.\n");exit(1);}case '^':return pow(operand1, operand2);default:return 0;}//计算表达式结果double evaluateExpression(char *expression) Stack operandStack;Stack operatorStack;initStack(&operandStack);initStack(&operatorStack);int length = strlen(expression);for (int i = 0; i < length; i++)//忽略空格if (expression[i] == ' ')continue;}//数字直接入栈if (isdigit(expression[i]))double num = 0;while (i < length && (isdigit(expression[i]) , expression[i] == '.'))num = num * 10 + (expression[i] - '0');i++;}i--;push(&operandStack, num);}//左括号入栈else if (expression[i] == '(')push(&operatorStack, expression[i]);}//右括号出栈并执行运算,直到遇到左括号else if (expression[i] == ')')while (peek(&operatorStack) != '(')double operand2 = pop(&operandStack);double operand1 = pop(&operandStack);char operator = pop(&operatorStack);double result = performOperation(operand1, operand2, operator);push(&operandStack, result);}pop(&operatorStack);}//运算符出栈并执行运算,直到栈空或者遇到优先级较低的运算符elsewhile (peek(&operatorStack) != -1 &&getPriority(expression[i]) <= getPriority(peek(&operatorStack))) double operand2 = pop(&operandStack);double operand1 = pop(&operandStack);char operator = pop(&operatorStack);double result = performOperation(operand1, operand2, operator);push(&operandStack, result);}push(&operatorStack, expression[i]);}}//处理剩下的运算符while (peek(&operatorStack) != -1)double operand2 = pop(&operandStack);double operand1 = pop(&operandStack);char operator = pop(&operatorStack);double result = performOperation(operand1, operand2, operator);push(&operandStack, result);}return pop(&operandStack); // 返回最终结果int maichar expression[MAX_EXPRESSION_SIZE];printf("Enter an arithmetic expression: ");fgets(expression, MAX_EXPRESSION_SIZE, stdin);double result = evaluateExpression(expression);printf("Result = %.2f\n", result);return 0;```这个计算器可以实现基本的四则运算,支持括号和浮点数。

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

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

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

科学计算器源代码

科学计算器源代码

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

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

c语言实现虚拟计算器代码

c语言实现虚拟计算器代码

c语言实现虚拟计算器代码以下是一个简单的C语言虚拟计算器代码示例: c.#include <stdio.h>。

int main() {。

char operator;float num1, num2, result;printf("请输入运算符(+, -, , /): ");scanf("%c", &operator);printf("请输入两个数字: ");scanf("%f %f", &num1, &num2);switch(operator) {。

case '+':result = num1 + num2; break;case '-':result = num1 num2; break;case '':result = num1 num2; break;case '/':if(num2 != 0) {。

result = num1 / num2;} else {。

printf("错误,除数不能为0\n"); return 1; // 退出程序。

}。

break;default:printf("错误,无效的运算符\n");return 1; // 退出程序。

}。

printf("结果: %f %c %f = %f\n", num1, operator,num2, result);return 0;}。

这段代码首先要求用户输入运算符和两个数字,然后根据用户输入的运算符进行相应的计算,并输出结果。

在这个示例中,我们使用了switch语句来根据不同的运算符执行不同的计算操作。

另外,我们还对除数为0的情况进行了处理,以避免出现除以0的错误。

当然,这只是一个简单的示例代码,实际的虚拟计算器可能会更复杂,包括更多的功能和更完善的用户界面。

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

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

超详细因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用Windows窗体应用程序,并命名为Calc,如下图所示:向窗体中拖入需要的控件,如下图所示:(完成效果图)结果显示区(作者博客左边的文本框)是TextBox控件,并修改其name为txtShow,按键0~9 为Button 控件,并将其name分别修改为btn_O、btn_1、btn_2、btn_3、btn_4、btn_5、btn_6、btn_7、btn_8、btn_9;按键【负数】的name值修改为btn_sign,按键【.】的name修改为btn_dot,按键【+ - * / 】的name 值分别修改为btn_add、btn_sub、btn_mul、btn_div,按键【=】的name值修改为btn_equ,按键【倒数】的name值修改为btn_rev,按键【平方】的name值修改为btn_sqr,按键【开方】的name值修改为btn_sqrt。

右边的计算器图片空间是PictureBox ,作者博客控件是LinkLabel ,可以不添加,以上所有控件均可按照需求添加,只保留自己需要的按钮控件和textbox控件即可。

三、代码部分(含解释),采用switch多分支语句编写using System;using System.Drawing;using System.Collections;using ponentModel;usingusing System.Data;namespace Calc{/// <summary>///温柔一刀C#简易计算器的实现/// </summary>public class CalcFormForm{private Button btnprivate Button btnprivate Button btnprivate Button btnprivate Button btnprivate Button btn_5;private Button btn_6;private Button btn_7;private Button btn_8;private Button btn_9;private Button btn_add;private Button btn_sub;private Button btn_mul;private Button btn_div;private Button btn_sqrt;private Button btn_sign;private Button btn_equ;private Button btn_dot;private Button btn_rev;private TextBox txtShow;private Button btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;/// <summary>/// 必需的设计器变量。

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

超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用Windows窗体应用程序,并命名为Calc,如下图所示:二、向窗体中拖入需要的控件,如下图所示:(完成效果图)结果显示区(作者博客左边的文本框)是TextBox控件,并修改其name为txtShow ,按键0~9为Button控件,并将其name分别修改为btn_0、btn_1、btn_2、btn_3、btn_4、btn_5、btn_6、btn_7、btn_8、btn_9;按键【负数】的name值修改为btn_sign,按键【.】的name 修改为btn_dot,按键【+ - * /】的name值分别修改为btn_add、btn_sub、btn_mul、btn_div,按键【=】的name值修改为btn_equ,按键【倒数】的name值修改为btn_rev,按键【平方】的name值修改为btn_sqr,按键【开方】的name值修改为btn_sqrt。

右边的计算器图片空间是PictureBox,作者博客控件是LinkLabel,可以不添加,以上所有控件均可按照需求添加,只保留自己需要的按钮控件和textbox控件即可。

三、代码部分(含解释),采用switch多分支语句编写using System;using System.Drawing;using System.Collections;using ponentModel;usingusing System.Data;namespace Calc{///<summary>///温柔一刀C#简易计算器的实现///</summary>public class CalcFormForm{private Button btn_0;private Button btn_1;private Button btn_2;private Button btn_3;private Button btn_4;private Button btn_5;private Button btn_6;private Button btn_7;private Button btn_8;private Button btn_9;private Button btn_add;private Button btn_sub;private Button btn_mul;private Button btn_div;private Button btn_sqrt;private Button btn_sign;private Button btn_equ;private Button btn_dot;private Button btn_rev;private TextBox txtShow;private Button btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;///<summary>///必需的设计器变量。

///</summary>private ponentModel.Container components = null; public CalcForm(){//// Windows 窗体设计器支持所必需的//InitializeComponent();//// TODO: 在InitializeComponent 调用后添加任何构造函数代码//}///<summary>///清理所有正在使用的资源。

///</summary>protected override void Dispose( bool disposing ){if( disposing ){if (components != null){components.Dispose();}}base.Dispose( disposing );}#region Windows Form Designer generated code///<summary>///设计器支持所需的方法- 不要使用代码编辑器修改///此方法的内容。

///</summary>private void InitializeComponent(){ponentResourceManager resources = newponentResourceManager(typeof(CalcForm));this.btn_9 = new Button();this.txtShow = new TextBox();this.btn_8 = new Button();this.btn_7 = new Button();this.btn_div = new Button();this.btn_sqrt = new Button();this.btn_4 = new Button();this.btn_5 = new Button();this.btn_6 = new Button();this.btn_1 = new Button();this.btn_2 = new Button();this.btn_3 = new Button();this.btn_0 = new Button();this.btn_mul = new Button();this.btn_sub = new Button();this.btn_sign = new Button();this.btn_equ = new Button();this.btn_add = new Button();this.btn_dot = new Button();this.btn_sqr = new Button();this.btn_rev = new Button();this.pictureBox1 = new PictureBox();this.linkLabel1 = new LinkLabel();((ponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();this.SuspendLayout();//// btn_9//this.btn_9.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_9.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_9.ForeColor = System.Drawing.Color.Black;this.btn_9.Location = new System.Drawing.Point(126, 37);this.btn_ = "btn_9";this.btn_9.Size = new System.Drawing.Size(59, 31);this.btn_9.TabIndex = 0;this.btn_9.Tag = "9";this.btn_9.Text = "9";this.btn_eVisualStyleBackColor = false;this.btn_9.Click += new System.EventHandler(this.btn_0_Click);//// txtShow//this.txtShow.Location = new System.Drawing.Point(4, 6); = "txtShow";this.txtShow.ReadOnly = true;this.txtShow.Size = new System.Drawing.Size(242, 21);this.txtShow.TabIndex = 1;this HorizontalAlignment.Right;//// btn_8//this.btn_8.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_8.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_8.ForeColor = System.Drawing.Color.Black;this.btn_8.Location = new System.Drawing.Point(66, 37);this.btn_ = "btn_8";this.btn_8.Size = new System.Drawing.Size(59, 31);this.btn_8.TabIndex = 2;this.btn_8.Tag = "8";this.btn_8.Text = "8";this.btn_eVisualStyleBackColor = false;this.btn_8.Click += new System.EventHandler(this.btn_0_Click);//// btn_7//this.btn_7.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_7.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_7.ForeColor = System.Drawing.Color.Black;this.btn_7.Location = new System.Drawing.Point(4, 37);this.btn_ = "btn_7";this.btn_7.Size = new System.Drawing.Size(59, 31);this.btn_7.TabIndex = 3;this.btn_7.Tag = "7";this.btn_7.Text = "7";this.btn_eVisualStyleBackColor = false;this.btn_7.Click += new System.EventHandler(this.btn_0_Click);//// btn_div//this.btn_div.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_div.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_div.ForeColor = System.Drawing.Color.Red;this.btn_div.Location = new System.Drawing.Point(187, 37);this.btn_ = "btn_div";this.btn_div.Size = new System.Drawing.Size(59, 31);this.btn_div.TabIndex = 4;this.btn_div.Text = "/";this.btn_eVisualStyleBackColor = false;this.btn_div.Click += new System.EventHandler(this.btn_div_Click);//// btn_sqrt//this.btn_sqrt.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_sqrt.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_sqrt.ForeColor = System.Drawing.Color.Black;this.btn_sqrt.Location = new System.Drawing.Point(253, 37);this.btn_ = "btn_sqrt";this.btn_sqrt.Size = new System.Drawing.Size(59, 31);this.btn_sqrt.TabIndex = 5;this.btn_sqrt.Text = "开方";this.btn_eVisualStyleBackColor = false;this.btn_sqrt.Click += new System.EventHandler(this.btn_sqrt_Click);//// btn_4//this.btn_4.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_4.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_4.ForeColor = System.Drawing.Color.Black;this.btn_4.Location = new System.Drawing.Point(4, 72);this.btn_ = "btn_4";this.btn_4.Size = new System.Drawing.Size(59, 31);this.btn_4.TabIndex = 6;this.btn_4.Tag = "4";this.btn_4.Text = "4";this.btn_eVisualStyleBackColor = false;this.btn_4.Click += new System.EventHandler(this.btn_0_Click);//// btn_5//this.btn_5.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_5.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_5.ForeColor = System.Drawing.Color.Black;this.btn_5.Location = new System.Drawing.Point(66, 72);this.btn_ = "btn_5";this.btn_5.Size = new System.Drawing.Size(59, 31);this.btn_5.TabIndex = 7;this.btn_5.Tag = "5";this.btn_5.Text = "5";this.btn_eVisualStyleBackColor = false;this.btn_5.Click += new System.EventHandler(this.btn_0_Click);//// btn_6//this.btn_6.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_6.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_6.ForeColor = System.Drawing.Color.Black;this.btn_6.Location = new System.Drawing.Point(126, 72);this.btn_ = "btn_6";this.btn_6.Size = new System.Drawing.Size(59, 31);this.btn_6.TabIndex = 8;this.btn_6.Tag = "6";this.btn_6.Text = "6";this.btn_eVisualStyleBackColor = false;this.btn_6.Click += new System.EventHandler(this.btn_0_Click);//// btn_1//this.btn_1.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_1.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_1.ForeColor = System.Drawing.Color.Black;this.btn_1.Location = new System.Drawing.Point(4, 108);this.btn_ = "btn_1";this.btn_1.Size = new System.Drawing.Size(59, 31);this.btn_1.TabIndex = 9;this.btn_1.Tag = "1";this.btn_1.Text = "1";this.btn_eVisualStyleBackColor = false;this.btn_1.Click += new System.EventHandler(this.btn_0_Click);//// btn_2//this.btn_2.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_2.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_2.ForeColor = System.Drawing.Color.Black;this.btn_2.Location = new System.Drawing.Point(66, 108);this.btn_ = "btn_2";this.btn_2.Size = new System.Drawing.Size(59, 31);this.btn_2.TabIndex = 10;this.btn_2.Tag = "2";this.btn_2.Text = "2";this.btn_eVisualStyleBackColor = false;this.btn_2.Click += new System.EventHandler(this.btn_0_Click);//// btn_3//this.btn_3.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_3.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_3.ForeColor = System.Drawing.Color.Black;this.btn_3.Location = new System.Drawing.Point(126, 108);this.btn_ = "btn_3";this.btn_3.Size = new System.Drawing.Size(59, 31);this.btn_3.TabIndex = 11;this.btn_3.Tag = "3";this.btn_3.Text = "3";this.btn_eVisualStyleBackColor = false;this.btn_3.Click += new System.EventHandler(this.btn_0_Click);//// btn_0//this.btn_0.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_0.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_0.ForeColor = System.Drawing.Color.Black;this.btn_0.Location = new System.Drawing.Point(4, 143);this.btn_ = "btn_0";this.btn_0.Size = new System.Drawing.Size(59, 31);this.btn_0.TabIndex = 12;this.btn_0.Tag = "0";this.btn_0.Text = "0";this.btn_eVisualStyleBackColor = false;this.btn_0.Click += new System.EventHandler(this.btn_0_Click);//// btn_mul//this.btn_mul.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_mul.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_mul.ForeColor = System.Drawing.Color.Red;this.btn_mul.Location = new System.Drawing.Point(187, 72);this.btn_ = "btn_mul";this.btn_mul.Size = new System.Drawing.Size(59, 31);this.btn_mul.TabIndex = 13;this.btn_mul.Text = "*";this.btn_eVisualStyleBackColor = false;this.btn_mul.Click += new System.EventHandler(this.btn_mul_Click);//// btn_sub//this.btn_sub.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_sub.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_sub.ForeColor = System.Drawing.Color.Red;this.btn_sub.Location = new System.Drawing.Point(187, 108);this.btn_ = "btn_sub";this.btn_sub.Size = new System.Drawing.Size(59, 31);this.btn_sub.TabIndex = 14;this.btn_sub.Text = "-";this.btn_eVisualStyleBackColor = false;this.btn_sub.Click += new System.EventHandler(this.btn_sub_Click);//// btn_sign//this.btn_sign.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_sign.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_sign.ForeColor = System.Drawing.Color.Red;this.btn_sign.Location = new System.Drawing.Point(66, 143);this.btn_ = "btn_sign";this.btn_sign.Size = new System.Drawing.Size(59, 31);this.btn_sign.TabIndex = 15;this.btn_sign.Text = "负数";this.btn_eVisualStyleBackColor = false;this.btn_sign.Click += new System.EventHandler(this.btn_sign_Click);//// btn_equ//this.btn_equ.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_equ.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_equ.ForeColor = System.Drawing.Color.Red;this.btn_equ.Location = new System.Drawing.Point(253, 143);this.btn_ = "btn_equ";this.btn_equ.Size = new System.Drawing.Size(59, 31);this.btn_equ.TabIndex = 16;this.btn_equ.Text = "=";this.btn_eVisualStyleBackColor = false;this.btn_equ.Click += new System.EventHandler(this.btn_equ_Click);//// btn_add//this.btn_add.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_add.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_add.ForeColor = System.Drawing.Color.Red;this.btn_add.Location = new System.Drawing.Point(187, 143);this.btn_ = "btn_add";this.btn_add.Size = new System.Drawing.Size(59, 31);this.btn_add.TabIndex = 17;this.btn_add.Text = "+";this.btn_eVisualStyleBackColor = false;this.btn_add.Click += new System.EventHandler(this.btn_add_Click);//// btn_dot//this.btn_dot.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_dot.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_dot.ForeColor = System.Drawing.Color.Black;this.btn_dot.Location = new System.Drawing.Point(126, 143);this.btn_ = "btn_dot";this.btn_dot.Size = new System.Drawing.Size(59, 31);this.btn_dot.TabIndex = 18;this.btn_dot.Text = ".";this.btn_eVisualStyleBackColor = false;this.btn_dot.Click += new System.EventHandler(this.btn_dot_Click);//// btn_sqr//this.btn_sqr.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_sqr.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_sqr.ForeColor = System.Drawing.Color.Black;this.btn_sqr.Location = new System.Drawing.Point(253, 72);this.btn_ = "btn_sqr";this.btn_sqr.Size = new System.Drawing.Size(59, 31);this.btn_sqr.TabIndex = 19;this.btn_sqr.Text = "平方";this.btn_eVisualStyleBackColor = false;this.btn_sqr.Click += new System.EventHandler(this.btn_sqr_Click);//// btn_rev//this.btn_rev.BackColor = System.Drawing.SystemColors.ActiveBorder;this ImageLayout.Center;this SystemColors.ButtonFace;this Color.WhiteSmoke;this.btn_rev.Font = new System.Drawing.Font("黑体", 10.5F,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));this.btn_rev.ForeColor = System.Drawing.Color.Red;this.btn_rev.Location = new System.Drawing.Point(253, 108);this.btn_ = "btn_rev";this.btn_rev.Size = new System.Drawing.Size(59, 31);this.btn_rev.TabIndex = 20;this.btn_rev.Text = "倒数";this.btn_eVisualStyleBackColor = false;this.btn_rev.Click += new System.EventHandler(this.btn_rev_Click);//// pictureBox1//this.pictureBox1.Image =((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));this.pictureBox1.Location = new System.Drawing.Point(319, 6); = "pictureBox1";this.pictureBox1.Size = new System.Drawing.Size(100, 168);this.pictureBox1.TabIndex = 21;this.pictureBox1.TabStop = false;//// linkLabel1//this.linkLabel1.AutoSize = true;this.linkLabel1.Location = new System.Drawing.Point(253, 13); = "linkLabel1";this.linkLabel1.Size = new System.Drawing.Size(53, 12);this.linkLabel1.TabIndex = 22;this.linkLabel1.TabStop = true;this.linkLabel1.Text = "作者博客";this.linkLabel1.LinkClicked +=new LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);//// CalcForm//this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);this.ClientSize = new System.Drawing.Size(427, 181);this.Controls.Add(this.linkLabel1);this.Controls.Add(this.pictureBox1);this.Controls.Add(this.btn_rev);this.Controls.Add(this.btn_sqr);this.Controls.Add(this.btn_dot);this.Controls.Add(this.btn_add);this.Controls.Add(this.btn_equ);this.Controls.Add(this.btn_sign);this.Controls.Add(this.btn_sub);this.Controls.Add(this.btn_mul);this.Controls.Add(this.btn_0);this.Controls.Add(this.btn_3);this.Controls.Add(this.btn_2);this.Controls.Add(this.btn_1);this.Controls.Add(this.btn_6);this.Controls.Add(this.btn_5);this.Controls.Add(this.btn_4);this.Controls.Add(this.btn_sqrt);this.Controls.Add(this.btn_div);this.Controls.Add(this.btn_7);this.Controls.Add(this.btn_8);this.Controls.Add(this.txtShow);this.Controls.Add(this.btn_9);this FormBorderStyle.FixedDialog;this.MaximizeBox = false; = "CalcForm";this FormStartPosition.CenterScreen;this.Text = "C#编写计算器;this.Load += new System.EventHandler(this.CalcForm_Load);((ponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();this.ResumeLayout(false);this.PerformLayout();}#endregionpublic const int NULL = 0; // 定义操作码public const int ADD = 1;public const int SUB = 2;public const int MUL = 3;public const int DIV = 4;public const int SQR = 5;public const int SQRT = 6;public const int NODOT = 0; // 定义是否点击了小数点public const int HASDOT = 1;private double res = 0; // 记录结果数private double tmp = 0; // 当前输入的操作数private int opt = NULL; // 记录操作码private int dot = NODOT; // 记录是否点击了小数点private int num = 0; // 记录输入操作数的个数private int dotnum = 0; // 记录小数点部分的个数///<summary>///应用程序的主入口点。

相关文档
最新文档